javascript - jquery/javascript 手动换行文本

标签 javascript jquery

我正在尝试手动换行覆盖图像的文本。目前,我有一个文本输入框,用户可以在其中输入句子,覆盖文本会更新每次按键时显示的文本。覆盖文本使用文本转换来弯曲和 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/

相关文章:

javascript - 为什么我的 CSV 没有写入任何数据?

javascript - 我无法让所有的 Javascript 计算一起工作以获得总计

javascript - 在 Backbone 单击事件中使用 JSON key

javascript - 使用 jQuery 链接到 Accordion 中的部分

javascript - console.log 上显示什么类型的数据?

javascript - 单击复选框时未触发下拉列表复选框事件

javascript - 检查对象是否包含数组

jquery - Html5 拖放 svg 元素

javascript - 滚动 safari bug 上元素的增长高度

javascript - 如何使用数据表在表格上显示更少的文本?