简体   繁体   中英

How to toggle style in animation using jQuery?

How can I add opacity: 0.5 to li when it's clicked and toggle the opacity back to opacity:1 when clicked again with animation?

$('li').on('click', function () {
    $(this).animate({
        opacity: 0.5
    }, 500, function () {
        $(this).toggleClass('completed');
    });
});

Is there any simple solution like toggling between classes or do I need to add logic to check the current opacity and change accordingly? I don't want to change markup or CSS but would like to do it through jQuery.

We can use math for that :)

$('li').on('click', function () {
    $(this).animate({
        opacity: (0.5 / $(this).css("opacity"))
    }, 500, function () {
        $(this).toggleClass('completed');
    });
});

You can do it like following.

 $('li').on('click', function () { if ($(this).is(':animated')) return; //ignore click while animating var opacity = $(this).css('opacity') == 1 ? 0.5 : 1; $(this).animate({ opacity: opacity }, 500, function () { $(this).toggleClass('completed'); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Click Here</li> <li>Click Here</li> </ul> 

All you need is a flag

$('li').on('click', function () {

    var opacity,
        flag = $(this).data('flag');

    if ( flag ) {
        opacity = 1;
    } else {
        opacity = 0.5;
    }

    $(this).animate({
        opacity: opacity
    }, 500, function () {
        $(this).toggleClass('completed');
        $(this).data('flag', !flag);
    });
});

(Really verbose on purpose)

 $('li').on('click', function () { var opacity, flag = $(this).data('flag'); if ( flag ) { opacity = 1; } else { opacity = 0.5; } $(this).animate({ opacity: opacity }, 500, function () { $(this).toggleClass('completed'); $(this).data('flag', !flag); }); }); 
 li {color : red; cursor: pointer; margin: 20px 0 0 0;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Click to fade</li> <li>Click to fade</li> <li>Click to fade</li> <li>Click to fade</li> <li>Click to fade</li> <li>Click to fade</li> </ul> 

The less verbose version

$('li').on('click', function () {
    var flag = $(this).data('flag');

    $(this).fadeTo(500, flag ? 1 : 0.5, function() {
        $(this).toggleClass('completed').data('flag', !flag);
    });
});

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