Add linebreak to textContent or innerText only - in Chrome

戏子无情 提交于 2019-11-29 13:54:18

问题


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.

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.

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>

回答1:


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

Change c1.textContent to c1.innerText and it will display the line break.




回答2:


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

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



来源:https://stackoverflow.com/questions/9330671/add-linebreak-to-textcontent-or-innertext-only-in-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!