[英]Apply CSS if text exceeds a certain length
如果元素中的文本超过一定长度,是否有办法将CSS应用于元素。 例如<p class="foo">123456789</p>
。
然后,当元素中的文本超过x个字符时,将应用新类
<p class="foo text-exceeds-X-chars">12345678910101010101</p>
使用jQuery text() ,然后使用length
。 如果满足条件,请使用addClass()来应用该类
if($('p.foo').text().length > 20){
$('p.foo').addClass('my-class');
}
如果您有多个p.foo
元素,请执行
$('p.foo').each(function(){
if($(this).text().length > 20){
$(this).addClass('my-class');
}
});
我建议使用addClass
回调函数:
$('p.foo').addClass(function() {
return $.trim(this.textContent).length > 10
? 'text-exceeds-X-chars'
: null;
});
没有内置过滤器或选择器,因此您必须手动执行此操作。 我们的想法是选择所有有问题的元素并在循环中测试每个元素的长度:
$('.foo').each(function() {
if ($(this).text().length > x) {
$(this).addClass('text-exceeds-X-chars');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.