jquery 段落中的每一行自动换行

z0qdvdin  于 2023-02-12  发布在  jQuery
关注(0)|答案(2)|浏览(158)

我有一个<div>元素,它将显示一个没有换行符的段落,如示例所示

<div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum
</div>

这里的文本将根据其容器的宽度拆分为若干行,我试图将自动调整大小的每一行 Package 到一个span元素中。但我没有做到这一点,因为我们无法使用\n找到行的结尾。有什么方法可以实现这一点吗?
注意-我找到一个答案,当我搜索Can I wrap each line of multi-line text in a span?。但问题是不是类似于此,这里我有一个测试在单行,没有换行符。但上述问题有换行符的每一行

pkln4tw6

pkln4tw61#

为了能够计算出什么时候有一个新的行,我们必须首先知道句子的最后一个单词是什么时候。为了找出答案,我们会给每个单词贴上标签。然后我们取每个单词的Y坐标。如果有差异,我们就知道一个新的规则已经开始了。
用于更新https://github.com/nielsreijnders/textSplitter/blob/master/src/index.ts

// Openingtag & closingtag has to be a string!!
function splitLines(container, openingtag, closingtag) {

    // Get the spans in the paragraph 
    var spans = container.children,

        top = 0,

        // set tmp as a string 
        tmp = '';

    // Put spans on each word, for now we use the <n> tag because, we want to save 5 bytes:)
    container.innerHTML = container.textContent.replace(/\S+/g, '<n>$&</n>');   

    // Loop through each words (spans) 
    for (let i = 0; i < spans.length; i++) {

        // Get the height of each word
        var rect = spans[i].getBoundingClientRect().top;

        // If top is different as the last height of the word use a closingtag and use an opentag after that
        if (top < rect) tmp += closingtag + openingtag;
        top = rect;

        // Add the spans + space between each word
        tmp += spans[i].textContent + ' ';
    }

    // Add the lines back to the paragraph 
    container.innerHTML = tmp += closingtag;
}

x一个一个一个一个x一个一个二个一个x一个一个三个一个
当你调整窗口大小的时候你必须更新线条!

toe95027

toe950272#

这应该能满足你的要求,或者接近于你的要求。

function trimByPixel(str, width) {
    var spn = $('<span style="visibility:hidden"></span>').text(str).appendTo('body');
    var txt = str;
    while (spn.width() > width) { txt = txt.slice(0, -1); spn.text(txt + "..."); }
    return txt;
}

var stri = $(".str").text();

function run(){
  var s = trimByPixel(stri, $(".str").width()).trim()
  stri = stri.replace(s,"")
  $(".result").append("<span>"+s+"</span>");
  
  if(stri.trim().length > 0){
    run();
  }
}

run();
    • 演示**

x一个一个一个一个x一个一个二个一个x一个一个三个一个

相关问题