有什么方法可以通过jQuery截取CSS截断的文本吗? [英] Is there any way to grab the CSS truncated text via jQuery?

查看:79
本文介绍了有什么方法可以通过jQuery截取CSS截断的文本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从CSS截断的元素中获取HTML,但似乎无法正确处理.

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

例如:

<span id=mySpan style=white-space:nowrap;overflow:hidden;text-overflow:ellipsis;width:50px>This is the contents of the span tag.  It should truncate with an ellipsis if it is longer than 50px.</span>

如果我使用标准的jQuery方式获取HTML,则会获取全文,而不是截断的版本.我不确定是否有可能.

If I use the standard jQuery way to grab the HTML, I get the full text, not the truncated version. I'm not sure if it is even possible.

html = jQuery('#mySpan').html();
text = jQuery('#mySpan').text();

均返回全文.我很困惑.

Both return the full text. I'm stumped.

推荐答案

您可以计算出它:

$.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

演示

当然,这仅适用于具有overflow:hidden;text-overflow:ellipsis的元素,但是在没有text-overflow:ellipsis的情况下很容易适应:只需删除+"…".

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).

这篇关于有什么方法可以通过jQuery截取CSS截断的文本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆