Remove formatting from a contentEditable div

前端 未结 8 725
醉话见心
醉话见心 2020-12-25 11:40

I have a contentEditable Div and I want remove any formatting especially for copy and paste text.

相关标签:
8条回答
  • 2020-12-25 12:07
    document.querySelector('div[contenteditable="true"]').addEventListener("paste", function(e) {
            e.preventDefault();
            var text = e.clipboardData.getData("text/plain");
            document.execCommand("insertHTML", false, text);
        });
    

    It is simple: add a listener to the "paste" event and reeformat clipboard contents.

    Here another example for all containers in the body:

    [].forEach.call(document.querySelectorAll('div[contenteditable="true"]'), function (el) {
        el.addEventListener('paste', function(e) {
            e.preventDefault();
            var text = e.clipboardData.getData("text/plain");
            document.execCommand("insertHTML", false, text);
        }, false);
    });
    

    Saludos.

    0 讨论(0)
  • 2020-12-25 12:10

    Have you tried using innerText?

    ADDED:

    If you want to strip markup from content pasted into the editable div, try the old hack of creating a temporary div -- see example below.

    <!DOCTYPE html>
    <html>
    
    <head> 
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
      <title>Strip editable div markup</title>
    
      <script type="text/javascript">
        function strip(html) {
          var tempDiv = document.createElement("DIV");
          tempDiv.innerHTML = html;
          return tempDiv.innerText;
        }
      </script>
    </head>
    
    <body>
      <div id="editableDiv" contentEditable="true"></div>
      <input type="button" value="press" onclick="alert(strip(document.getElementById('editableDiv').innerText));" />
    </body>
    
    </html>
    
    0 讨论(0)
提交回复
热议问题