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

后端 未结 5 827
南方客
南方客 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 10:52

    The algorithm to calculate all the factors perfectly using only javascript would be too complex.

    With css3 there is line-clamp

    But this works only on modern browsers.

    p{
     margin:20px;
     overflow: hidden;
     text-overflow: ellipsis;
     display: -webkit-box;
     -webkit-line-clamp: 3;
     -webkit-box-orient: vertical;
    }
    

    DEMO

    http://jsfiddle.net/MM29r/

    this allows you to set the number of lines you want to display before adding the 3 dots.

    now you want 300px... so:

    var p=document.getElementsByTagName('p')[0],
    lineheight=parseInt(window.getComputedStyle(p).getPropertyValue("line-height"));
    var lines=Math.floor(300/lineheight);
    p.style['-webkit-line-clamp']=lines;
    

    so this gives you an element that is 300px or less

    DEMOS

    http://jsfiddle.net/MM29r/1/

    http://jsfiddle.net/MM29r/2/

    NEEDED VALUES: line-height

    Now if you want to make the box exactly 300px height just add margins or paddings to the paragraphs.But that depends on your preferences.

    if you have some questions just ask.

    Note

    every js function that adds 3 dots at the end by calculating the words would be to resources intensive to apply in a real world website.

    a better approach would be to calculate every paragraph one time and add the clamped result to a db or store it in the static website.

    but then again every browser displays fonts in a different way.

    EDIT

    Here is a different way to display partial content. Using max-height & -webkit-column-count

    https://stackoverflow.com/a/20691677/2450730

    DEMO

    http://jsfiddle.net/HNF3d/10/

    the support is slightly higher than line-clamp and you are abe to display the whole content.

    EDIT2

    Fading image at the bottom.

    p{
     width:300px;
     max-height:300px;
     overflow:hidden;
    }
    p:before{
     content:"";
     display:block;
     position:absolute;
     margin-top:240px;
     background:-webkit-linear-gradient(top,rgba(255,255,255,0) 0%,rgba(255,255,255,1) 80%);
     height:60px;
     width:300px;
    }
    

    http://jsfiddle.net/MM29r/9/

    EDIT3

    fading image old browsers (use real images links, not base64)

    http://jsfiddle.net/MM29r/13/

提交回复
热议问题