zoukankan      html  css  js  c++  java
  • 多行文本超出部分以省略号显示

    看到这样的效果,首先想到的是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;
        }
    });

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

  • 相关阅读:
    新的工作电脑 神州优雅A550i7
    职责链模式(Chain of Responsibility)
    访问者模式(Visitor)
    单例模式(Singleton)
    解释器模式(Interpreter)
    迭代器模式(Iterator)
    解决 Visual Stuido 工具栏中的工具重置后,恢复回来。
    WCF 一步一步 发布 WCF服务 到 Windows 服务 (图)
    桥接模式(Bridge)与合成/聚合复用原则(CARP)
    dbentry访问带密码的Access
  • 原文地址:https://www.cnblogs.com/wyhlightstar/p/6916397.html
Copyright © 2011-2022 走看看