带有textContent的自动换行

时间:2018-07-18 06:50:09

标签: javascript

我正在尝试通过Javascript将长文本插入HTML。这是我的代码。

  function introStory(){
  var txt = document.getElementById("paragraph");
  txt.setAttribute('style', 'white-space: pre;');
  txt.textContent = ""
  txt.textContent += "\"Kill them all!\"\r\n\r\nThey came without warning. The humans, beasts, and holy hosts attacks my village and family. They slaughtered all my neighbors, killed my mother and my father."
}

对于CSS:

#paragraph{
     overflow: hidden;
     border: 1px solid rgba(255,255,255,0.7);
     text-align: left;
     word-wrap: break-word;
     overflow-wrap: break-word;
 }

插入到div命名段落中的文本不会像我希望的那样打断单词。它继续到指定的div之外。我在这里做错什么了吗?

1 个答案:

答案 0 :(得分:1)

使用white-space: pre-wrap; or white-space: pre-line;代替white-space: pre;

堆栈片段

function introStory(){
  var txt = document.getElementById("paragraph");
  txt.setAttribute('style', 'white-space: pre-wrap;');
  txt.textContent = ""
  txt.textContent += "\"Kill them all!\"\r\n\r\nThey came without warning. The humans, beasts, and holy hosts attacks my village and family. They slaughtered all my neighbors, killed my mother and my father."
}

introStory();
#paragraph{
     overflow: hidden;
     border: 1px solid rgba(255,255,255,0.7);
     text-align: left;
 }
<div id="paragraph"></div>