最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery addClass to element if css has style - Stack Overflow

programmeradmin4浏览0评论

please have a look at following question and answer, the seccond answer (with the many upvotes) Jquery: How to check if the element has certain css class/style

looks like this:

if ($('#yourElement').css('position') == 'absolute') {
    // true
}

so this is awesome but I would like something like

if ($('#yourElement').css('position') == 'absolute') {
    $(this).addClass('xxx');
}

so the element with the ID "yourElement" gets a class added

what is the easyest way to do that

please have a look at following question and answer, the seccond answer (with the many upvotes) Jquery: How to check if the element has certain css class/style

looks like this:

if ($('#yourElement').css('position') == 'absolute') {
    // true
}

so this is awesome but I would like something like

if ($('#yourElement').css('position') == 'absolute') {
    $(this).addClass('xxx');
}

so the element with the ID "yourElement" gets a class added

what is the easyest way to do that

Share Improve this question edited May 23, 2017 at 12:21 CommunityBot 11 silver badge asked Mar 4, 2013 at 12:35 carambacaramba 22.5k20 gold badges93 silver badges133 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

You could do it this way:

$('#yourElement').addClass(function(index, currentClass) {
    return $(this).css('position') == 'absolute' ? 'xxx' : '';
});

For more information on the syntax take a look at the API for .addClass().

var yourElement = $('#yourElement');    
if (yourElement.css('position') == 'absolute') {
        yourElement.addClass('xxx');
}
// Cache your element first
var $element = $('#yourElement');

if ($element.css('position') == 'absolute') {
    $element.addClass('xxx');
}

Assign $('#yourElement') to a variable. Then perform the check on that variable and add the class to it as well. This simply saves on the number of queries made to the DOM with the $() function in your example and in the likely possibility that further manipulation is required.

For example:

var your_element = $('#yourElement');
if (your_element.css('position') == 'absolute') { your_element.addClass('xxx'); }
发布评论

评论列表(0)

  1. 暂无评论