我有一个可能包含长文本的元素。我正在寻找一个 jQuery 函数来检测文本是否溢出元素的宽度或高度,如果是,则必须向父元素添加一个类。 (我不是在寻找 text-ellipsis 属性。)
如何做到这一点?我已经开始了fiddle here 。显然,它不适用于 $(elm).text().width()
。如何获取text()的宽度?
最佳答案
克隆
到一个临时元素,更改样式
并与原始元素进行比例比较,最后删除该临时对象并返回比较结果。
$.expr[':'].truncated = function (obj) {
var $this = $(obj);
var $c = $this
.clone()
.css({
display: 'inline',
width: 'auto',
visibility: 'hidden'
})
.appendTo('body');
var c_width = $c.width();
$c.remove();
if (c_width > $this.width())
return true;
else
return false;
};
$(".title:truncated").addClass("text-style");
.title {
width: 300px;
overflow: hidden;
height: 20px;
text-overflow: ellipsis;
white-space: nowrap;
}
.text-style {
color: red;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="title">A very long title title title - if I break I must have the class "text-style" appended</div>
<div class="title">A very long title title title </div>
关于jquery - 如果文本溢出父元素,请添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34088513/