简体   繁体   English

粘贴到contentEditable div时如何保留onclick

[英]How to preserve onclick when pasted to a contentEditable div

I have a link and a contentEditable div. 我有一个链接和一个contentEditable div。 The link has a onclick property. 链接具有onclick属性。 When I copied the link and pasted it into the contentEditable div, the onclick property was removed. 当我复制链接并将其粘贴到contentEditable div中时, onclick属性被删除。 Is there anyway to preserve the property in contentEditable? 无论如何,要在contentEditable中保留该属性吗?

Details 细节

描述

Snippet 片段

 <html> <head> </head> <body> <a href="#" onclick="handleClick()">Click me</a> <div style="border: 1px solid black; min-width: 100px;" contenteditable="true"> </div> <script> function handleClick() { console.log("clicked"); } </script> </body> </html> 

The browser strips event handlers for you to prevent XSS. 浏览器会为您剥离事件处理程序以防止XSS。 But if you're sure it's ok to keep potentially dangerous things in the pasted HTML, you can customize onPaste handler: 但是,如果确定可以在粘贴的HTML中保留潜在危险的东西是可以的,则可以自定义onPaste处理程序:

const editable = document.querySelector('[contenteditable]');
editable.addEventListener('paste', function(event) {
    const dataTransfer = event.clipboardData;
    const html = dataTransfer.getData('text/html');
    document.execCommand('insertHTML', false, html);
    event.preventDefault();
});

This is just a proof of concept, and there's a lot more you would need to do to make this work reliably in different browsers. 这仅仅是一个概念证明,并有大量的越多,你需要做的,使这项工作可靠地在不同的浏览器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何防止 CSS 被粘贴到 contenteditable div - How to prevent CSS from being pasted in a contenteditable div 更改可信的div文本时如何保留插入位置? - How do I preserve the caret position when changing a contenteditable div's text? Angular contenteditable div 限制粘贴内容 - Angular contenteditable div restrict pasted content WordPress 编辑器如何在复制和粘贴时保留文本格式? - How does WordPress editor preserve formatting of text when copy and pasted? 如何在剪切/粘贴/移动后保留contentEditable DIV中与XML相关的数据 - How to preserve data associated with XML inside contentEditable DIV after cut/paste/move 在 contenteditable div 中按回车键时如何添加新 div - How to add new div when hitting enter key in contenteditable div 放置 cursor 并聚焦在 contenteditable div onclick - Placing cursor and focus inside contenteditable div onclick 如何使用 JavaScript 检测图像是否已粘贴或拖放到内容可编辑区域? - How do I detect, with JavaScript, if an image was pasted or dropped into a contenteditable area? 如何限制粘贴在 contenteditable 区域中的文本样式? - How do I restrict the style of the text pasted in a contenteditable area? 从 contenteditable div 中去除 HTML 格式,但在粘贴时保留换行符? - Strip HTML formatting from contenteditable div but preserve line breaks on paste?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM