Cross-browser multi-line text overflow with ellipsis appended within a fixed width and height

前端 未结 25 2442
栀梦
栀梦 2020-11-22 16:19

I made an image for this question to make it easier to understand.

Is it possible to create an ellipsis on a

with a fixed width and multiple
25条回答
  •  清酒与你
    2020-11-22 16:49

    Just a quick basic idea.

    I was testing with the following markup:

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis et dui. Nunc porttitor accumsan orci id luctus. Phasellus ipsum metus, tincidunt non rhoncus id, dictum a lectus. Nam sed ipsum a lacus sodales eleifend. Vestibulum lorem felis, rhoncus elementum vestibulum eget, dictum ut velit. Nullam venenatis, elit in suscipit imperdiet, orci purus posuere mauris, quis adipiscing ipsum urna ac quam.

    And CSS:

    #fos { width: 300px; height: 190px; overflow: hidden; }
    #fos p { padding: 10px; margin: 0; }
    

    Applying this jQuery will accomplish the desired result:

    var $p = $('#fos p');
    var divh = $('#fos').height();
    while ($p.outerHeight() > divh) {
        $p.text(function (index, text) {
            return text.replace(/\W*\s(\S)*$/, '...');
        });
    }
    

    It repeatedly tries to remove the last word of the text until it reaches the desired size. Because of the overflow: hidden; the process remains invisible and even with JS turned off the result remains 'visually correct' (without the "..." of course).

    If you combine this with a sensible truncation on the server-side (that leaves only a small overhead) then it will run quicker :).

    Again, this is not a complete solution, just an idea.

    UPDATE: Added a jsFiddle Demo.

提交回复
热议问题