標籤:... 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實現多行省略