javascript 在 contentEditable 中将 HTML 转换为纯文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15125217/
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-10-26 23:35:19  来源:igfitidea点击:

Convert HTML to plain text in contentEditable

javascriptjqueryhtmltextcontenteditable

提问by Alex

I have a contentEditableand I strip the formatting of pasted content on('paste')by catching the event. Then I focus a textarea, paste the content in there, and copy the value. Pretty much the answer from here. The problem is that I can't do this:

我有一个contentEditable,我on('paste')通过捕获事件来去除粘贴内容的格式。然后我聚焦一个 textarea,将内容粘贴在那里,然后复制该值。几乎来自here的答案。问题是我不能这样做:

$("#paste-output").text($("#area").val());

because that would replace my entire content with the pasted text. So I need to paste the content at caret position. I put together a script that does that:

因为这会用粘贴的文本替换我的整个内容。所以我需要将内容粘贴在插入符号位置。我整理了一个脚本来做到这一点:

pasteHtmlAtCaret($("#area").val());

// pastes CTRL+V content at caret position
function pasteHtmlAtCaret(html) {
  var sel, range;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();
      var el = document.createElement("div");
      el.innerHTML = html;
      var frag = document.createDocumentFragment(), node, lastNode;
      while ((node = el.firstChild)) {
        lastNode = frag.appendChild(node);
      }
      range.insertNode(frag);

      if (lastNode) {
        range = range.cloneRange();
        range.setStartAfter(lastNode);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
      }
    }
  } else if (document.selection && document.selection.type != "Control") {
    document.selection.createRange().pasteHTML(html);
  }
}

The only problem is that it pastes HTML content, at caret position using the htmlvariable. How can I transform that into plain text? I tried adding the jQuery .text(html)to variable without luck. Something like this might help:

唯一的问题是它使用html变量在插入符号位置粘贴 HTML 内容。如何将其转换为纯文本?我尝试将 jQuery 添加.text(html)到变量中,但没有运气。像这样的事情可能会有所帮助:

el.textContent||el.innerText;

Any ideas or a better solution? Thanks!

任何想法或更好的解决方案?谢谢!



EDIT:Thanks to the answers below I modified my code and solved the issue. I basically copied the value of textareainto a divand grabbed only its .text():

编辑:感谢下面的答案,我修改了我的代码并解决了这个问题。我基本上将 的值复制textarea到 adiv并只抓取了它的.text()

// on paste, strip clipboard from HTML tags if any
$('#post_title, #post_content').on("paste", function() {
    var text = $('<div>').html($("#area").val()).text();
    pasteHtmlAtCaret(text);
  }, 20);
});

采纳答案by Alex

Upon request from Jonathan Hobbs I am posting this as the answer. Thanks to the answers above I modified my code and solved the issue. I basically copied the value of textarea into a div and grabbed only its .text():

应 Jonathan Hobbs 的要求,我将其发布为答案。感谢上面的答案,我修改了我的代码并解决了这个问题。我基本上是将 textarea 的值复制到一个 div 中,并且只抓取了它的 .text():

// on paste, strip clipboard from HTML tags if any
$('#post_title, #post_content').on("paste", function() {
  setTimeout(function(){
    var text = $('<div>').html($("#area").val()).text();
    pasteHtmlAtCaret(text);
  }, 20);
});

回答by Shehabic

  1. Create an external div,
  2. Put your html in that div,
  3. Copy the text from that div
  4. Insert it at the cursor's position.
  1. 创建一个外部div,
  2. 把你的 html 放在那个 div 中,
  3. 从该 div 复制文本
  4. 将其插入到光标位置。

回答by TomWan

Replace tag solution:

更换标签解决方案:

http://jsfiddle.net/tomwan/cbp1u2cx/1/

http://jsfiddle.net/tomwan/cbp1u2cx/1/

var $plainText = $("#plainText");
var $linkOnly = $("#linkOnly");
var $html = $("#html");

$plainText.on('paste', function (e) {
    window.setTimeout(function () {
        $plainText.html(removeAllTags(replaceStyleAttr($plainText.html())));
    }, 0);
});

$linkOnly.on('paste', function (e) {
    window.setTimeout(function () {
        $linkOnly.html(removeTagsExcludeA(replaceStyleAttr($linkOnly.html())));
    }, 0);
});

function replaceStyleAttr (str) {
    return str.replace(/(<[\w\W]*?)(style)([\w\W]*?>)/g, function (a, b, c, d) {
        return b + 'style_replace' + d;
    });
}

function removeTagsExcludeA (str) {
    return str.replace(/<\/?((?!a)(\w+))\s*[\w\W]*?>/g, '');
}

function removeAllTags (str) {
    return str.replace(/<\/?(\w+)\s*[\w\W]*?>/g, '');
}

回答by Sebazzz

The solution I used is to set the innerText of the element on blur:

我使用的解决方案是将元素的 innerText 设置为模糊:

$element.on('blur', () => this.innerText = this.innerText);

$element.on('blur', () => this.innerText = this.innerText);

This keeps the whitespace, but strips the formatting. It may work acceptable in your scenario as well.

这会保留空格,但会去除格式。它在您的场景中也可以接受。