Apply CSS if text exceeds a certain length

Is there a way to apply a CSS to an element if the text within the element exceeds a certain length. For instance <p class="foo">123456789</p> .

Then, when the text within the element exceeds x characters a new class is applied

<p class="foo text-exceeds-X-chars">12345678910101010101</p>

我建议使用addClass回调函数:

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

Use jQuery text(), then, use length . If the condition is fulfilled, use addClass() to apply the class

if($('p.foo').text().length > 20){
    $('p.foo').addClass('my-class');
}

If you have multiple p.foo elements, do

$('p.foo').each(function(){
    if($(this).text().length > 20){
        $(this).addClass('my-class');
    }
});

There is not built-in filter or selector for this, so you will have to do it manually. The idea is to select all elements in question and test the length of each of them in loop:

$('.foo').each(function() {
    if ($(this).text().length > x) {
        $(this).addClass('text-exceeds-X-chars');
    }
});
链接地址: http://www.djcxy.com/p/85858.html

上一篇: 如何使用git正确使用GreaseMonkey脚本?

下一篇: 如果文字超过特定长度,则应用CSS