在一个范围中包装段落的每一行

时间:2018-03-16 11:28:26

标签: javascript jquery html

我有一个<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>

这里的文本会根据容器的宽度分成若干行,我试图将每个自动调整大小的行包装成span元素。但是我没能这样做,因为我们找不到使用\n的行的结尾是否有任何方法可以实现此目的?

注意 - 当我搜索Can I wrap each line of multi-line text in a span?时,我找到了答案。但是questin不是这个,这里我有一个单行测试,没有换行符。但上面的问题在每一行都有换行符

2 个答案:

答案 0 :(得分:2)

在这里

// 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 + opentag;
        top = rect;

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

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

演示

function splitLines(container, opentag, closingtag) {
    var spans = container.children,
        top = 0,
        tmp = '';
    container.innerHTML = container.textContent.replace(/\S+/g, '<n>$&</n>');
    for (let i = 0; i < spans.length; i++) {
        var rect = spans[i].getBoundingClientRect().top;
        if (top < rect) tmp += closingtag + opentag;
        top = rect;
        tmp += spans[i].textContent + ' ';
    }
    container.innerHTML = tmp += closingtag;
}

splitLines(document.querySelectorAll('p')[0], '<span>','</span>')
* {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  line-height: 22px;
}

h1 {
  letter-spacing: 1px;
  border-bottom: 1px solid #eaecef;
  padding-bottom: .5em;
}

p {
  font-size: 14px;
  width: 350px;
}

p span:nth-child(even) {
  color: #34495e;
}

a {
  color: black; 
  margin-right: 5px;
}
<h1>TextSplitter </h1>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui.</p>

  

通知

调整窗口大小时必须更新行!

答案 1 :(得分:1)

这应该做你想要的,或接近它。

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();

<强>演示

&#13;
&#13;
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();
&#13;
.str{
width:300px;
}

.result span{
display:block
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="str"> 
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>

<div class="result"></div>
&#13;
&#13;
&#13;