我有一个包含输入标签的前置标签。有一个绑定(bind)到 pre 标记的粘贴事件监听器。
$(function() {
if (document.querySelector('pre[contenteditable="true"]') != null) {
document.querySelector('pre[contenteditable="true"]').addEventListener("paste", function(e) {
e.preventDefault();
//alert("test");
var text = e.clipboardData.getData("text/plain");
document.execCommand("insertHtml", false, text);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="previewEmailBody" class="blurbBody" placeholder="Reply" style="display:block" contenteditable="true">Testing
<input class="emailBodyToken" name="[Test]" size="54" value="[Test]" >
Testing</pre>
现在 - 如果我点击输入元素并粘贴文本 - 它不会更新输入元素,而是更新 pre 元素中的文本。
上述行为仅在 firefox 中观察到。在 chrome 中,它会按预期更新输入元素。我也希望在 Firefox 中有相同的行为。请提出解决此问题的方法。
最佳答案
如果事件针对 input
元素,则需要让事件发生。
$(function() {
if (document.querySelector('pre[contenteditable="true"]') != null) {
document.querySelector('pre[contenteditable="true"]').addEventListener("paste", function(e) {
if (e.explicitOriginalTarget.tagName !== "INPUT")
{
e.preventDefault();
//alert("test");
var text = e.clipboardData.getData("text/plain");
document.execCommand("insertHtml", false, text);
}
});
}
});
更新的 JS fiddle
关于javascript - Document.execCommand 不更新当前事件元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49899735/