简体   繁体   中英

Do something if body has a class of “ie.” Do something else if body does not have a class of “ie.”

I think I wrote this wrong because it's not working as I intended.

I want it to work like this:

If body does not have the ie class, and if body.single #project-wrapper has the activated class, it should add the grayscale class and change the opacity .

If body has the ie class, and if body.single #project-wrapper has the activated class, it should just change the opacity .

How can I rewrite the code below to reflect what I wrote above?

if (!$(body).hasClass('ie')) {
    if ( $('body.single #project-wrapper').hasClass('activated') ) {
        $('article.project').addClass('grayscale').css('opacity', '0.4');
    }
}

if ($(body).hasClass('ie')) {
    if ( $('body.single #project-wrapper').hasClass('activated') ) {
        $('article.project').css('opacity', '0.4');
    }
}

Need to use element selector for body. There is no variable called body so you should be having an error like ReferenceError: body is not defined in your console

if ($('body').hasClass('ie')) {
    if ($('body.single #project-wrapper').hasClass('activated')) {
        $('article.project').css('opacity', '0.4');
    }
} else {
    if ($('body.single #project-wrapper').hasClass('activated')) {
        $('article.project').addClass('grayscale').css('opacity', '0.4');
    }
}

Since the condition $('body.single #project-wrapper').hasClass('activated') is common you can do something like

if ($('body.single #project-wrapper').hasClass('activated')) {
    if ($('body').hasClass('ie')) {
        $('article.project').css('opacity', '0.4');
    } else {
        $('article.project').addClass('grayscale').css('opacity', '0.4');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM