粘贴事件在可编辑的内容中无法正常工作

时间:2019-06-28 07:28:37

标签: javascript jquery events contenteditable

当用户粘贴文本时,我正在尝试删除regular expresion可编辑内容中的换行符。

问题在于,正则表达式仅在您第二次粘贴某些东西之后才起作用。我还需要keyupkeypress事件来处理示例中未包含的其他内容(限制的字符数)。

我的代码怎么了?

$(document).on("keyup keypress paste", "#myContentEditable", function(e) {
  if (e.type === "paste") {
    $(this).html($(this).text().replace(/[\n\r]/g, ""));
  }

  if (e.which === 13) {
    e.preventDefault();
    return false;
  }
});
#myContentEditable {
  border: 1px solid lightblue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myContentEditable" contenteditable="plaintext-only" max="130" contenteditable="true">This is content editable. Remove break lines of the pasted text only works at the second time</div>
<hr>
<p>Try to paste this text:</p>
<p>Massa enim nec dui nunc mattis enim ut tellus elementum. Accumsan sit amet nulla facilisi morbi tempus iaculis urna id.<br><br> Nunc lobortis mattis aliquam faucibus purus in massa.</p>

1 个答案:

答案 0 :(得分:2)

问题是因为paste事件在contenteditable div的实际HTML更新之前就触发了。

您可以改用input事件来解决此问题:

$(document).on("input", "#myContentEditable", function(e) {
  $(this).html($(this).text().replace(/[\n\r]/g, ""));
});
#myContentEditable {
  border: 1px solid lightblue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myContentEditable" contenteditable="plaintext-only" max="130" contenteditable="true">This is content editable. Remove break lines of the pasted text only works at the second time</div>
<hr>
<p>Try to paste this text:</p>
<p>Massa enim nec dui nunc mattis enim ut tellus elementum. Accumsan sit amet nulla facilisi morbi tempus iaculis urna id.<br><br> Nunc lobortis mattis aliquam faucibus purus in massa.</p>