Element: paste event - Web APIs 编辑
The paste
event is fired when the user has initiated a "paste" action through the browser's user interface.
Bubbles | Yes |
---|---|
Cancelable | Yes |
Interface | ClipboardEvent |
Event handler property | onpaste |
If the cursor is in an editable context (for example, in a <textarea>
or an element with contenteditable
attribute set to true
) then the default action is to insert the contents of the clipboard into the document at the cursor position.
A handler for this event can access the clipboard contents by calling getData()
on the event's clipboardData
property.
To override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventDefault()
, and then insert its desired data manually.
It's possible to construct and dispatch a synthetic paste
event, but this will not affect the document's contents.
Examples
Live example
HTML
<div class="source" contenteditable="true">Try copying text from this box...</div>
<div class="target" contenteditable="true">...and pasting it into this one</div>
CSS
div.source, div.target {
border: 1px solid gray;
margin: .5rem;
padding: .5rem;
height: 1rem;
background-color: #e9eef1;
}
JS
const target = document.querySelector('div.target');
target.addEventListener('paste', (event) => {
let paste = (event.clipboardData || window.clipboardData).getData('text');
paste = paste.toUpperCase();
const selection = window.getSelection();
if (!selection.rangeCount) return false;
selection.deleteFromDocument();
selection.getRangeAt(0).insertNode(document.createTextNode(paste));
event.preventDefault();
});
Result
Specifications
Specification | Status |
---|---|
Clipboard API and events | Working Draft |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论