【问题标题】:Paste event not working as expected in a content editable [duplicate]粘贴事件在可编辑的内容中未按预期工作[重复]
【发布时间】:2019-06-28 07:28:37
【问题描述】:

当用户粘贴文本时,我正在尝试使用 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>

【问题讨论】:

    标签: javascript jquery events contenteditable


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-01-16
      • 2021-04-22
      • 2016-09-02
      • 2019-04-18
      • 1970-01-01
      • 2019-07-16
      • 2016-02-04
      • 1970-01-01
      • 2012-01-19
      相关资源
      最近更新 更多