//单词自动换行
function insertLineBreaks(msg, maxLength) {
var words = msg.split(" ");
var result = "";
var currentLineLength = 0;
for (var i = 0; i < words.length; i++) {
if (currentLineLength + words[i].length > maxLength) {
result += "\n";
currentLineLength = 0;
}
result += words[i] + " ";
currentLineLength += words[i].length + 1;
}
return result.trim();
}
msg.value =
"A fox saw some grapes hanging from a vine. She wanted to eat them but they were too high for her to reach. She went away saying, “The grapes are sour.” This is an example of cognitive dissonance, where people rationalize their failure to attain something they desire by disparaging it.";
msg.value = insertLineBreaks(msg.value, 37);
[重点]使用pre标签它不会重新排列文本规则
【注意】一定要加上whith-spce标签不然输入文字不会换行