Javascript 将 contenteditable 文本的 innerHTML 转换为普通字符串

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

Convert innerHTML of a contenteditable text to normal string

javascriptcsshtmlcontenteditable

提问by Basj

I use a content-editable element :

我使用内容可编辑元素:

<span id="myinput" contenteditable="true">This is editable.</span>

and

document.getElementById('myinput').innerHTML

to read its content from Javascript.

从 Javascript 读取其内容。

But the result is :

但结果是:

  • "blah "=> innerHTML = "blah &nbsp "

  • "bonjour\n bonstheitroad"=> innerHTML = "bonjour<br>bonstheitroad"(Firefox) and innerHTML = "bonjour<div>bonstheitroad</div>"(Chrome)

  • maybe there are lots of other things that are translated into HTML...

  • "blah "=> innerHTML = "blah &nbsp "

  • "bonjour\n bonstheitroad"=> innerHTML = "bonjour<br>bonstheitroad"(Firefox) 和innerHTML = "bonjour<div>bonstheitroad</div>"(Chrome)

  • 也许还有很多其他的东西被翻译成 HTML ......

How to convert innerHTMLinto normal text?

如何转换innerHTML成普通文本?

(i.e. in my 2 examples : "blah "and "bonjour\n bonstheitroad")

(即在我的两个例子中:"blah ""bonjour\n bonstheitroad"

回答by EvilEpidemic

Try using;

尝试使用;

// for IE
document.getElementById('myinput').innerText

// for everyone else
document.getElementById('myinput').textContent

In terms of finding linebreaks, etc, consider;

在寻找换行符等方面,请考虑;

el = document.getElementById('myinput');
var nodes = el.childNodes;
var text = '';

for(var i = 0; i < nodes.length; i++) {                        
    switch(nodes[i].nodeName) {
        case '#text'    : text = text + nodes[i].nodeValue;   break;
        case 'BR'       : text = text + '\n';      break;
    }
}
console.log(text);

回答by Bart

Due to the fact this behaviour is not consistent in different browsers, you have to implement this yourself:

由于此行为在不同浏览器中不一致,您必须自己实现:

var convert = (function() {
    var convertElement = function(element) {
        switch(element.tagName) {
            case "BR": 
                return "\n";
            case "P": // fall through to DIV
            case "DIV": 
                return (element.previousSibling ? "\n" : "") 
                    + [].map.call(element.childNodes, convertElement).join("");
            default: 
                return element.textContent;
        }
    };

    return function(element) {
        return [].map.call(element.childNodes, convertElement).join("");
    };
})();

In action: http://jsfiddle.net/koyd8h59/1/

在行动:http: //jsfiddle.net/koyd8h59/1/

Of course you'll need to add your own code if you want to use <h1>and other block-level tags.

当然,如果您想使用<h1>和其他块级标记,则需要添加自己的代码。