Element: paste事件

 

当用户在浏览器用户界面发起“粘贴”操作时,会触发paste事件。

冒泡可取消接口                 ClipboardEvent

事件处理属性          onpaste

如果光标位于可编辑的上下文中(例如,在 <textarea> 或者 contenteditable 属性设置为 true的元素),则默认操作是将剪贴板的内容插入光标所在位置的文档中。

事件处理程序可以通过调用事件的 clipboardData 属性上的 getData()访问剪贴板内容。

要覆盖默认行为(例如,插入一些不同的数据或转换剪贴板的内容),事件处理程序必须使用 event.preventDefault(),取消默认操作,然后手动插入想要的数据。

可以构造和分派合成的paste事件,但这不会影响文档内容。

举例

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

 

规范

规范 状态
Clipboard API and events Working Draft

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
paste eventChrome Full support 58Edge Full support YesFirefox Full support YesIE Full support 11Opera Full support 45Safari Full support YesWebView Android Full support 58Chrome Android Full support 58Firefox Android Full support YesOpera Android Full support 43Safari iOS ? Samsung Internet Android ?
clipboardDataChrome Full support 58Edge Full support YesFirefox Full support 22IE No support NoOpera Full support 45Safari Full support YesWebView Android Full support 58Chrome Android Full support 58Firefox Android Full support 22Opera Android Full support 43Safari iOS ? Samsung Internet Android ?

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown

另见