html:
<style> .userName{ float:left; width: 76px; height: 40px; line-height: 20px; text-align: center; margin: 0 2px 0 2px; border:1px solid #ccc; overflow: hidden; } p{ word-wrap: break-word; margin:0px; padding:0px; } </style> <div class="userName"><p>张三</p></div> <div class="userName"><p>李四</p></div> <div class="userName"><p>大范围降雨降温来袭_-nvfiudsa8339n()__+若冬天回归】明后天,江南及以北降温4-10度,北方周五最冷,太原、北京、石家庄竟不足10度,南方周六最冷,看图;雨雪将铺展,呼和浩特、拉萨雨夹雪,大多城市下雨,山东、</p></div> <div class="userName"><p>为公务员服务</p></div> |
js:
/* * 多行文本溢出省略 */ $.fn.ellipsis = function(){ $(this).each(function(i){ var divH = $(this).height(); var $p = $("p", $(this)).eq(0); while ($p.outerHeight() > divH) { $p.text($p.text().replace(/(\s)*([\w\W]{1})(\.\.\.)?$/, "...")); }; if($p.outerHeight()<=(divH/2)){ $p.css("line-height", divH+"px"); } }); }; $(".userName").ellipsis(); |
js代码来自于http://www.99447.com/art-gg-98.html,但他的代码遇到下划线等特殊字符会在正则替换时死循环导致浏览器卡死,我修改了他的正则表达式.
效果: