Javascript 从 contentEditable div 中删除格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6899659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:40:35  来源:igfitidea点击:

Remove formatting from a contentEditable div

javascriptjqueryhtmlformattingcontenteditable

提问by Garth Humphreys

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

我有一个 contentEditable Div,我想删除任何格式,特别是对于复制和粘贴文本。

回答by Isaac Limón

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.

萨卢多斯。

回答by Sam Dutton

Have you tried using innerText?

你试过使用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.

如果您想从粘贴到可编辑 div 的内容中去除标记,请尝试创建临时 div 的旧技巧——请参见下面的示例。

<!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>

回答by Daniel - SDS Group

Was looking for answer to this for ages and ended up writing my own.

多年来一直在寻找这个问题的答案,最终写了我自己的。

I hope this helps others. At the time of writing this it appears to work in ie9, latest chrome and firefox.

我希望这对其他人有帮助。在撰写本文时,它似乎可以在 ie9、最新的 chrome 和 firefox 中运行。

<div contenteditable="true" onpaste="OnPaste_StripFormatting(this, event);" />

<script type="text/javascript">

    var _onPaste_StripFormatting_IEPaste = false;

    function OnPaste_StripFormatting(elem, e) {

        if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) {
            e.preventDefault();
            var text = e.originalEvent.clipboardData.getData('text/plain');
            window.document.execCommand('insertText', false, text);
        }
        else if (e.clipboardData && e.clipboardData.getData) {
            e.preventDefault();
            var text = e.clipboardData.getData('text/plain');
            window.document.execCommand('insertText', false, text);
        }
        else if (window.clipboardData && window.clipboardData.getData) {
            // Stop stack overflow
            if (!_onPaste_StripFormatting_IEPaste) {
                _onPaste_StripFormatting_IEPaste = true;
                e.preventDefault();
                window.document.execCommand('ms-pasteTextOnly', false);
            }
            _onPaste_StripFormatting_IEPaste = false;
        }

    }

</script>

回答by Robson Hermes

I know it's been a while, but I had the same problem. On my case, it's a GWT application to make it even worse. Anyway, resolved the problem with:

我知道已经有一段时间了,但我遇到了同样的问题。就我而言,它是一个 GWT 应用程序,让它变得更糟。无论如何,解决了这个问题:

var clearText = event.clipboardData.getData('text/plain');
document.execCommand('inserttext', false, clearText);

See: https://jsfiddle.net/erikwoods/Ee3yC/

见:https: //jsfiddle.net/erikwoods/Ee3yC/

I preferred "inserttext" command instead of "insertHTML", because the documentation says it's exactly to insert plain text, so seems more suitable. See https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

我更喜欢“inserttext”命令而不是“insertHTML”,因为文档说它正是插入纯文本,所以看起来更合适。请参阅https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

回答by Justo

With Jquery you can use .text()method, so, when blur for example you can replace the content with the text content

使用 Jquery,您可以使用.text()方法,因此,例如,当模糊时,您可以将内容替换为文本内容

$("#element").blur(function(e) {
    $(this).html($(this).text());
});

回答by Matthias Hagemann

Try <div id="editableDiv" contentEditable="plaintext-only"></div>

尝试 <div id="editableDiv" contentEditable="plaintext-only"></div>

回答by Airhogs777

I'd like to add my solution to this issue:

我想为这个问题添加我的解决方案:

ContentEditableElement.addEventListener('input', function(ev) {
  if(ev.target.innerHTML != ev.target.textContent) {

    // determine position of the text caret
    var caretPos = 0,
      sel, range;
    sel = window.getSelection();
    if (sel.rangeCount) {
      range = sel.getRangeAt(0);
      var children = ev.target.childNodes;
      var keepLooping = true;
      for(let i = 0; keepLooping; i++) {
        if(children[i] == range.commonAncestorContainer || children[i] == range.commonAncestorContainer.parentNode) {
          caretPos += range.endOffset;
          keepLooping = false;
        } else {
          caretPos += children[i].textContent.length;
        }
      }

      // set the element's innerHTML to its textContent
      ev.target.innerHTML = ev.target.textContent;

      // put the caret where it was before
      range = document.createRange();
      range.setStart(ev.target.childNodes[0], caretPos);
      range.collapse(true);
      sel.removeAllRanges();
      sel.addRange(range);
    }
  }
});

(this isn't compatible with older versions of IE)

(这与旧版本的 IE 不兼容)

回答by Tim Down

You can't access the system clipboard so you'll need a hack. See this question: JavaScript get clipboard data on paste event (Cross browser)

您无法访问系统剪贴板,因此您需要破解。看到这个问题:JavaScript get clipboard data on paste event (Cross browser)