Is there any way to grab the CSS truncated text via jQuery?

后端 未结 2 964
一生所求
一生所求 2021-01-01 11:08

I am trying to grab the HTML from a CSS truncated element and can\'t seem to get it right.

For example:



        
2条回答
  •  爱一瞬间的悲伤
    2021-01-01 12:05

    You can compute it :

    $.fn.renderedText = function(){
      var o = s = this.text();
      while (s.length && (this[0].scrollWidth>this.innerWidth())){
        s = s.slice(0,-1);
        this.text(s+"…");
      }
      this.text(o);
      return s;
    }
    
    var renderedText = $("#mySpan").renderedText(); // this is your visible string
    

    Demonstration

    Of course this only works for an element with overflow:hidden;text-overflow:ellipsis but it's easy to adapt when there's no text-overflow:ellipsis: just remove the +"…".

    Note that this is compatible with all browsers and gives the exact result (the w3.org specifies that the … character is to be used by the browser).

提交回复
热议问题