javascript 仅将换行符添加到 textContent 或 innerText - 在 Chrome 中

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

Add linebreak to textContent or innerText only - in Chrome

javascripthtmlwysiwygcontenteditable

提问by cronoklee

This is a complicated one! Im working with contentEditable in Chrome and I'm experiencing a head melting problem. When I press the return key, Chrome inserts a new div into the innerHTML. This is fine and dandy. The problem is that the line break is nowhere to be found in the div's textContent. I really need to figure out a way to add the line break to the textContent in the same place as the div break in the innerHTML.

这是一个复杂的问题!我在 Chrome 中使用 contentEditable 并且遇到了头部熔化问题。当我按下返回键时,Chrome 会在 innerHTML 中插入一个新的 div。这很好,很花哨。问题是在 div 的 textContent 中找不到换行符。我真的需要想出一种方法,将换行符添加到 textContent 与innerHTML 中的div 分隔符相同的位置。

Any Ideas?

有任何想法吗?

UPDATE:

更新:

I can use innerText but then line breaks that are there when the page loads are ignored. I need consistency across one of these methods. In other words, I need textContent to show newly inputted line breaks or innerText to show line breaks that existed on page load.

我可以使用innerText,但是当页面加载被忽略时存在的换行符。我需要这些方法之一的一致性。换句话说,我需要 textContent 来显示新输入的换行符或 innerText 来显示页面加载时存在的换行符。

Here's an updated demo:

这是一个更新的演示:

function checkit() {
  var c1 = document.getElementById('c1')
  alert("TEXTCONTENT:\n" + c1.textContent + "\n\nINNERTEXT:\n" + c1.innerText + "\n\nINNERHTML:\n" + c1.innerHTML)
}
div {padding: 20px; border-bottom: 1px solid #CCC;}
<div><a href="#" onclick="checkit()">check it</a></div>

<div contentEditable="true" id="c1">click inside this <b>div</b>,
press return and then press <b>check it</b> above</div>

采纳答案by cronoklee

I've solved this by loading a different variable for each situation:

我通过为每种情况加载不同的变量来解决这个问题:

On page load, I use textContentwhich keeps line breaks intact. When the user starts typing, I use innerTextwhich recognises inserted page breaks. A simple if statement will do the trick!

在页面加载时,我使用textContent它保持换行符完整。当用户开始打字时,我使用innerTextwhich 识别插入的分页符。一个简单的 if 语句就可以解决问题!

回答by Dennis

This is because textContentis not aware of style. As a result, e.g., it displays hidden content.

这是因为textContent不知道风格。结果,例如,它显示隐藏的内容。

Change c1.textContentto c1.innerTextand it will display the line break.

更改c1.textContentc1.innerText,它将显示换行符。