CSS Multi Line ellipsis Cross Browser

前端 未结 5 565
小蘑菇
小蘑菇 2021-01-22 09:39

There is a \"div\" in my webpage that has fixed width and height.

Following css only works with single line text:

overflow: hidden;
text-overflow: ellips         


        
5条回答
  •  不思量自难忘°
    2021-01-22 09:46

    var explorer = detectIE();
    
    function detectIE() {
      var ua = window.navigator.userAgent;
      var msie = ua.indexOf('MSIE ');
      if (msie > 0) {
        // IE 10 or older => return version number
        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
      }
      var trident = ua.indexOf('Trident/');
      if (trident > 0) {
        // IE 11 => return version number
        var rv = ua.indexOf('rv:');
        return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
      }
      var edge = ua.indexOf('Edge/');
      if (edge > 0) {
        // Edge (IE 12+) => return version number
        return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
      }
      // other browser
      return false;
    }
    var firefox = navigator.userAgent.indexOf('Firefox') > -1;
    
    if ((explorer) || (firefox)) {
    
      var fontSize = $(".ellipsis-2").css('font-size');
      var fontSize = parseInt(fontSize, 10);
      var lineHeight = fontSize + 4;
      var height = lineHeight * 2;
      $(".ellipsis-2").css("line-height", lineHeight + "px");
      $(".ellipsis-2").css("height", height);
      $(".ellipsis-2").css({
        "overflow": "hidden",
        "position": "relative",
        "word-break": "break-all"
      });
    
      var divheight = $(".ellipsis-2").height();
      var lineheight = $(".ellipsis-2").css('line-height').replace("px", "");
      var countline = Math.round(divheight / parseInt(lineheight));
      // if you want to show 2 line 
      if (countline > 2) {
        $(".ellipsis-2").addClass("dotted");
      };
    
    }
    .ellipsis-2 {
      -webkit-hyphens: auto;
      -moz-hyphens: auto;
      -ms-hyphens: auto;
      hyphens: auto;
      position: relative;
    }
    
    .dotted:after {
      content: "...";
      position: absolute;
      bottom: 0;
      right: 0;
      background: #fff;
    }
    
    

    Reacts to content height. That is, you don't need to fix the height of your content containers. We expect no ellipsis here (unless your viewport is narrow)

提交回复
热议问题