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

后端 未结 2 945
一生所求
一生所求 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:06

    @dystroy has given a nice answer, here is another (more future-friendly) way to do this though.

    We can use document.caretPositionFromPoint. This is almost a FF only function, but most other browsers provide the same thing under their own function name and API. No I don't know what browsers have against devs but oh well...

    Our method works like this:

    • select element
    • get bounding client position
    • put it in the above function to get text offset position
    • subtract 3 from it to remove the ellipsis thingy from the offset
    • extract text according to that offset from textContent property

    Here is a quick demo (should work properly in Webkit and Gecko):

    function getRenderedText (el) {
      var pos = el.getBoundingClientRect();
      var offset, range;
      if (document.caretRangeFromPoint) {
        range = document.caretRangeFromPoint(pos.right, pos.top);
        offset = range.endOffset - 3;
      }
      else if (document.caretPositionFromPoint) {
        range = document.caretPositionFromPoint(pos.right, pos.top);
        offset = range.offset - 3;
      }
      else {
        console.error('Your browser is not supported yet :(');
      }
      return el.textContent.slice(0, offset);
    }
    
    console.log(getRenderedText(el));
    span {
      text-overflow: ellipsis;
      width: 40px;
      white-space: nowrap;
      display: block;
      overflow: hidden;
    }
    foo bar is so much awesome it is almost the bestest thing in the world. devs love foo bar. foo bar all the things!

    I have seen an error of maximum 1 character in some cases (weird fonts or edge cases), but most of the time, it works fine.

    Hope that helps!

提交回复
热议问题