javascript实现text-overflow:ellipsis效果

  对于一长串不会自动换行的字符串(如数字和字母连在一起的商品编号或者其他内容),会导致页面或者布局被撑破。

要自动换行可以使用word-break:break-all(IE和chrome支持,firefox不支持)。

javascript实现text-overflow:ellipsis效果

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<style>
.ellipsis{font-size:12px;line-height:15px;overflow: hidden;word-break:break-all}
</style>
<div style="height: 45px;width:60px;" class="ellipsis">1234567891a1234567891a1234567891a</div>

  现在要实现的功能是这些字符串能自动换行,显示为多行,同时实现text-overflow: ellipsis;效果。

text-overflow: ellipsis;效果需要结合overflow:hidden,在内容超出容器时才自动显示省略号(低版本的firefox不支持text-overflow: ellipsis;,至于从哪个版本支持text-overflow: ellipsis;效果不太清楚,firefox12测试没问题。)

javascript实现text-overflow:ellipsis效果

  不过text-overflow: ellipsis;和overflow:hidden结合使用时省略号出来了,但是word-break:break-all会失效,不会自动换行,只显示为一行。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<style>
.ellipsis{font-size:12px;line-height:15px;overflow: hidden;text-overflow:ellipsis;}
</style>
<div style="height: 45px;width:60px;" class="ellipsis">1234567891a1234567891a</div>


解决办法:用javascript自动格式化,实现text-overflow:ellipsis;并自动换行效果

javascript实现text-overflow:ellipsis效果

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<style>
.ellipsis{font-size:12px;line-height:15px;overflow: hidden;}
</style>
<div style="height: 45px;width: 30px;" class="ellipsis">1234567891a1234567891a</div>
<script>
    //@s:要格式化的字符串
    //@wl:每行显示的字符数
    //@hl:显示多少行
    function cutstring(s, wl, hl) {
        var total = wl * hl;
        if (s.length > total) s = s.substring(0, total - 3) + '...';

        s = s.replace(new RegExp('[\\s\\S]{' + wl + '}', 'g'), function ($0) { return $0 + '<br/>' });
        return s;
    }
    var div = document.getElementsByTagName('div');
    for (var i = 0; i < div.length; i++) div[i].innerHTML = cutstring(div[i].innerHTML, 5, 3);
</script>

 

加支付宝好友偷能量挖...


原创文章,转载请注明出处:javascript实现text-overflow:ellipsis效果

评论(0)Web开发网
阅读(296)喜欢(0)JavaScript/Ajax开发技巧