[英]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中保留该属性吗?
<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.