js實現多行省略

來源:互聯網
上載者:User

標籤:...   line   get   else   ++   外掛程式   ges   space   jquer   

雖然ie9逐步淘汰淘汰了,但是……為了相容ie8的多行省略功能,jq外掛程式ell

jQuery.fn.ell = function(count) {    for(var i = 0 ; i < $(this).length; i ++){        var ele = $(this).eq(i);        //words的width和height        var W = ele.width();        var H = ele.height();        //get element‘s children p        var p = ele.find(‘p‘);        //get element‘s lineheight        var lineHeight = parseFloat(ele.css(‘line-height‘) || ele.find(p).css(‘line-height‘));        if(count == 1) {            ele.find(p).css({                ‘width‘: W,                ‘text-overflow‘:‘ellipsis‘,                ‘white-space‘:‘nowrap‘,                ‘overflow‘:‘hidden‘            })        } else if (count >1) {            var divH = lineHeight*count;            if(H != ‘auto‘){                ele.css({                    ‘height‘: divH                });            }            //如果最的p的高度大於divH,那麼刪除末尾多餘行數的str            ele.each(function(i){                while (p.outerHeight() > divH) {                    p.text(p.text().replace(/(\s)*(\w+|\W)(\.\.\.)?$/, "..."));                };            })        }    }};

html、css和調用的js如下:

<style>.words {border: 1px solid #ddd; margin-bottom: 20px;/*以下三個屬性必須有*/width: 300px;overflow: hidden;line-height: 25px;/*以上三個屬性必須有*/}</style>
<script src="jquery.js"></script><script src="ell.js"></script>
<script> $(function(){ $(‘.words‘).ell(2); }) </script>


<body><div class="words"><p>我是超長文本標記語言我是超長文本標記語言我是超是超長文本標記語言我是超長文本標記語言</p></div><div class="words"><p>dsfasdsf asdsf asdsfas</p></div><div class="words"><p>是超長文本標記語言我是超是超長文本標記語言我是超是超長文本標記語言我是超是超長文本標記語言我是超是超長文本標記語言我是超是超長文本標記語言我是超是超長文本標記語言我是超是超長文本標記語言我是超是超長文本標記語言我是超</p></div>

效果:

 

js實現多行省略

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.