How to display only the first few lines of a div (clamping)?

后端 未结 5 801
南方客
南方客 2020-12-31 10:09

I have a list of divs in which I display the preview of longer documents. The documents use varying font styles. So I don\'t have a constant line height. Here i

5条回答
  •  有刺的猬
    2020-12-31 11:14

    Here what I would do in this case;

    First we have to get the div and find out the line-height so I am assuming you got your div as jQuery object.

    var $divToClamp = $("#");
    var $cloneDiv = $divToClamp.clone();
    $divToClamp.insertAfter($cloneDiv.html("A"));
    // created a new div as same place with the div to get same css, from parents, class etc.
    // i don t know how jQuery handles the ids you must check that
    var lineHeightToClamp = $cloneDiv.height() * 3;
    $cloneDiv.remove();
    // remove the clone we are done with it this does not work create clone div as fixed position back of the actual div and visibility hidden (not display:none)
    //now we now the line-height for 3 lines set the css
    $divToClamp.css({
          overflow : "hidden",
          lineHeight: lineHeightToClamp
        });
    

    some thing similar to this should fix you case but there might be some exceptions like margin of the div i am not sure $cloneDiv.height() includes them or not.

    also if there is another element (like span) in your div with different css that will also change the situation.

    Hope this helps.

提交回复
热议问题