我为我的小型 JavaScript 项目编写了一个函数,该函数将文本打印到 div 中,类似于老式游戏中的对话框。我已在下面的代码片段中包含了此函数的代码,尽管我相信这对于我的问题来说并不重要:
当我使用此功能时,当一个单词太长而无法容纳在一行中时,前几个字母通常会打印在当前行中。然后这个词跳到另一行并在那里结束。这会导致相当不愉快的效果。
我的问题是,我可以通过JS或CSS来阻止这种行为吗?有没有办法让函数提前知道新单词不适合当前行,并从头开始在新行中打印,从而避免跳转?
我尝试了目标 div 的各种自动换行设置,但无济于事。我真的不知道哪个 CSS 属性导致了这种行为。感谢您的帮助。
我想摆脱“演示”或“效果”等词中的跳词。我希望它们从头开始打印到新行。
代码片段 (也在JSFiddle)
async function echo(targetId, msg) {
let txtTarget = document.getElementById(targetId);
for (let i = 0; i < msg.length; i++) {
txtTarget.innerHTML += msg[i];
txtTarget.scrollTop = txtTarget.scrollHeight;
await this.sleep(55);
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const myMsg = 'This is a test message. I hope it clearly demonstrates what I\'m asking for. I want to get rid of the words jumping to new line effect. Instead, I want the words to be printed in a new line from the very beginning, if they\'re not going to fit in the current line.';
echo('message-box', myMsg);
body {
background: black;
color: ghostwhite;
}
#message-box {
width: 300px;
height: 200px;
border: 2px solid ghostwhite;
}
<div id="message-box"></div>
此方法利用两个元素。其中一种预先填充了整个消息,但使用透明文本。当每个字符被添加到“可见”元素时,“不可见”元素的第一个字符被删除。这种回填可以防止将要换行的单词出现在错误的行上。
async function echo(targetId, msg) {
let txtTarget = document.getElementById(targetId);
let visible = document.createElement('span');
let invisible = document.createElement('span');
invisible.style.color = 'transparent';
txtTarget.appendChild(visible);
txtTarget.appendChild(invisible);
invisible.innerHTML = msg;
for (let i = 0; i < msg.length; i++) {
visible.innerHTML += msg[i];
invisible.innerHTML = invisible.innerHTML.substring(1);
txtTarget.scrollTop = txtTarget.scrollHeight;
await this.sleep(55);
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const myMsg = 'This is a test message. I hope it clearly demonstrates what I\'m asking for. I want to get rid of the words jumping to new line effect. Instead, I want the words to be printed in a new line from the very beginning, if they\'re not going to fit in the current line.';
echo('message-box', myMsg);
body {
background: black;
color: ghostwhite;
}
#message-box{
width: 300px;
height: 200px;;
border: 2px solid ghostwhite;
}
<div id="message-box"></div>