JavaScript 剪贴板数据
本篇文章将介绍在 JavaScript 中检测粘贴事件上的剪贴板数据。
JavaScript 剪贴板数据
当用户通过浏览器 UI 启动粘贴操作时,将引发粘贴事件。
当光标位于可编辑上下文中时,默认操作是将剪贴板的内容粘贴到光标位置的文档中。 此事件的处理程序可以通过调用事件的 clipboardData 属性上的 getData()
来访问剪贴板的内容。
事件处理程序必须使用 event.preventDefault()
取消默认操作,并手动插入所需数据以覆盖默认行为。 可以创建并发送合成插入事件,但这不会影响文档的内容。
EventTarget 接口的 addEventListener()
方法配置了一个函数,只要指定的事件被传递到目标就会被调用。
举个例子,定义两个 div 元素。 一个是源头,一个是目的地。
Source Div 将包含要从中复制的数据,目标将是粘贴复制数据的位置。
<div class="source">Hello World!</div>
<div class="destination" contenteditable="true">...Good Bye!</div>
const destinationElement = document.querySelector('div.destination');
destinationElement.addEventListener('paste', (event) => {
const paste = (event.clipboardData || window.clipboardData).getData('text');
console.log(paste);
const selection = window.getSelection();
selection.deleteFromDocument();
selection.getRangeAt(0).insertNode(document.createTextNode(paste));
event.preventDefault();
});
在上面的示例中,我们首先使用 querySelector 选择目标元素。 选择元素后,我们将监听粘贴事件。
一旦用户粘贴数据,便会从事件中提取剪贴板数据。
从目标元素中删除原始内容,并将新内容插入到目标元素中。 尝试在任何支持粘贴事件的浏览器中运行上面的代码; 你会得到以下结果。
之前:
之后:
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。