简体   繁体   中英

jQuery toggle class animation

I found this code:

$('li input:checked').click(function() {
    $(this).parent().parent().toggleClass("uncheckedBoxBGColor", 1000);
});

It's working well, when a click the element for the first time. It fades the background color, but when I click it again, it delays for 1000 ms, and then flashes the other background color. I want it animated when it has the class, and when not, not only when clicked for the first time.

The jquery.toggleClass function isn't made for fading anyhow. See http://api.jquery.com/toggleClass/ for more details.

If you want to fade in/out the background color, try using the CSS3 transition feature like explained at Mozilla's side: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions .

This is easy with CSS transitions:

JS:

$('li input:checked').click(function() {
    $(this).parent().parent().toggleClass("uncheckedBoxBGColor", 1000);
});

CSS:

.uncheckedBoxBGColor {
  background-color: orange;
  /*other properties*/
  transition: background-color .3s;
}

This will add the effect whenever the class is turned ON, but when it doesn't have that class then there are no transitions defined. So instead, you can turn on this transition for ALL <LI> elements like so:

CSS:

li { transition: background-color .3s; }

OR for all <INPUT> elements following an <LI><INPUT> combination:

li input { transition: background-color .3s; }

You get the idea of it..

Maybe because you are using " input:checked "

try using

     $('li input[type=checkbox]').click(function () {
            $(this).parent().parent().toggleClass("uncheckedBoxBGColor", 1000);
        });

this is working for me.

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