我正在尝试手动换行覆盖图像的文本。目前,我有一个文本输入框,用户可以在其中输入句子,覆盖文本会更新每次按键时显示的文本。覆盖文本使用文本转换来弯曲和 reshape 文本,因此它不会自动换行。并且输入字段是大于包装切断长度的固定尺寸。
如果文本超过 10 个字符,我尝试换行,但这并不能说明它是否位于单词的中间。如何检测最后一个单词的结尾并在那里中断?
感谢您的帮助。
$("input[name='text']").keyup(function(event) {
var text = $(this).val();
var breakText = '';
while (text.length > 0) {
breakText += text.substring(0, 10) + '\n';
text = text.substring(10);
}
$("p.overlay").html(breakText);
});
无法向覆盖的文本添加宽度,因为它会像螺旋一样绕圈循环并自行返回。遗憾的是,宽度对文本没有换行效果。
最佳答案
尝试这个解决方案。希望对您有帮助
function explode(text, max) {
text = text.replace(/ +/g, " ").replace(/^ /, "").replace(/ $/, "");
if (typeof text === "undefined") return "";
if (typeof max === "undefined") max = 10;
if (text.length <= max) return text;
var exploded = text.substring(0, max);
text = text.substring(max);
if (text.charAt(0) !== " ") {
while (exploded.charAt(exploded.length - 1) !== " " && exploded.length > 0) {
text = exploded.charAt(exploded.length - 1) + text;
exploded = exploded.substring(0, exploded.length - 1);
}
if (exploded.length == 0) {
exploded = text.substring(0, max);
text = text.substring(max);
} else {
exploded = exploded.substring(0, exploded.length - 1);
}
} else {
text = text.substring(1);
}
return exploded + "\n" + explode(text);
}
var text = "My dog has fleas the quick brown fox jumps over the lazy dog etc.";
var exploded = explode(text);
document.write("<pre>");
document.write(exploded);
document.write("</pre>");
关于javascript - jquery/javascript 手动换行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22037671/