粘贴事件在内容可编辑中未按预期工作

Paste event not working as expected in a content editable

我试图在用户粘贴文本时使用 regular expresion 删除 contenteditable 中的换行符。

问题是正则表达式仅在您第二次粘贴内容后才起作用。我还需要 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>

问题是因为 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>