多行文本超出部分以省略号显示

看到这样的效果,首先想到的是css3,真的能解决吗?百度了一下还真的可以

  overflow : hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;

BUT,这是什么? -webkit- 这是指的在WebKit内核的浏览器才能看到的效果。所以这就是没有用的。

然后又看了其他的很多写法,并没有实现自己想要的效果。决定用js来控制

<p class="ellipsis">
我要在第二行的时候多余隐藏!我要在第二行的时候多余隐藏!我要在第二行的时候多余隐藏!我要在第二行的时候多余隐藏!我要在第二行的时候多余隐藏!我要在第二行的时候多余隐藏!我要在第二行的时候多余隐藏! </p>

.ellipsis{
     500px;
     line-height: 23px;
 }
$(function(){
    $(".ellipsis").each(function(){
        var maxwidth=36;
        if($(this).text().length>maxwidth){
           $(this).text($(this).text().substring(0,maxwidth));
           $(this).text($(this).html()+'…');
        }
     });
 })

需要先引入 jQuery.js

原理解析:设置一个最大的字符数,判断当文本内容超出了最大的字符数时,然后截取,最后显示。

此为效果:

2017-08-14  16:08:38 修改此博客

上面的代码没有考虑到内容中出现空格的情况(比如在写HTML时候的空格)

    function trim(str,is_global){
        var result;
        result = str.replace(/(^s+)|(s+$)/g,"");
        if(is_global.toLowerCase()=="g")
        {
            result = result.replace(/s/g,"");
        }
        return result;
    }

trim 方法是去除文本中的所有空格。

结合起来代码就变成这样了

$(function(){
    $(".ellipsis").each(function(){
        var maxwidth=110;
        var text =$(this).text();
        var _need ="g";
        var str = trim(text,_need);
        if($(this).text().length>maxwidth){
            $(this).text(str.substring(0,maxwidth));
            $(this).text($(this).html()+'…');
        }
    });

    function trim(str,is_global){
        var result;
        result = str.replace(/(^s+)|(s+$)/g,"");
        if(is_global.toLowerCase()=="g")
        {
            result = result.replace(/s/g,"");
        }
        return result;
    }
});

 *下载的插件没看懂怎么用了,愣是不出效果,只能自己写*

原文地址:https://www.cnblogs.com/wyhlightstar/p/6916397.html