如果文本超过一定长度,请应用CSS

Ada*_*cot 7 html javascript css jquery html5

如果元素中的文本超过一定长度,是否有办法将CSS应用于元素.例如<p class="foo">123456789</p>.

然后,当元素中的文本超过x个字符时,将应用新类

<p class="foo text-exceeds-X-chars">12345678910101010101</p>
Run Code Online (Sandbox Code Playgroud)

und*_*ned 3

我建议使用addClass回调函数:

$('p.foo').addClass(function() {
    return $.trim(this.textContent).length > 10
           ? 'text-exceeds-X-chars'
           : null;
});
Run Code Online (Sandbox Code Playgroud)