我(和许多其他人一样)正在尝试清理粘贴到 contentEditable iframe 中的文本。我没有使用 jQuery(它是一个非常古老的代码库)并且处理程序是这样附加的:
if (isIE) {
iframe.attachEvent("onpaste",handler);
}
else {
iframe.addEventListener("paste",handler,true);
}
这在 Firefox 和 Opera 中有效,但在 IE 10 和最新版本的 Chrome (29.0.1547.62) 中,处理程序永远不会被调用;我在处理程序的第一行放置了一个断点,但是当我粘贴一些文本时它没有到达断点并且粘贴的文本只是出现(未清理)。我尝试在 IE 9 模式下使用 IE10,但没有任何区别。其他处理程序似乎按预期被调用。
有人知道这里会发生什么吗?
TIA...
最佳答案
事实证明,iframe 加载了一个空白页面,然后以编程方式填充了内容。在重写 iframe 文档之前添加了事件监听器,这就是问题的原因。重写 iframe 内容后, 需要添加监听器。这是一个测试用例:
<html>
<head>
<title>Paste test&</title>
<script>
function handler() {
alert("Paste");
}
function register(iframe) {
//
// IE10 requires addEventListener to be used, so this
// is preferable to doing browser detection...
//
if (window.addEventListener) {
iframe.addEventListener("paste",handler,true);
}
else {
iframe.attachEvent("onpaste",handler);
}
}
function test() {
var iframe = document.getElementById("frm").contentWindow;
try {
var doc = iframe.document;
if (!doc) {
setTimeout(test,50);
return;
}
// register(iframe); // this won't work!
doc.open();
doc.write("<html><body>Paste text here: []</body></html>");
doc.close();
doc.body.contentEditable = true;
register(iframe); // this works!
}
catch (e) {
setTimeout(test,50);
return;
}
}
</script>
</head>
<body onLoad="test()">
Here is the iframe:
<p>
<iframe id="frm" src="blank.html" width="400" height="200"></iframe>
</body>
关于javascript - Chrome & IE : onpaste event not firing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18578916/