jQuery toggle element style but pausing briefly inbetween
I have an element which I am toggling the style of (like an on/off button). If it's currently 'on', change the style to 'off' and vice versa.
However, in some scenarios, I want to perform the above, but then revert to it's original state (cancelling out the toggle),开发者_如何学C but I want this to be reflected to the user by it's very brief change in style (so for 1/2 a second, it looks like it has changed style but then reverts back to it's original state.
I'm currently toggling the state of my button with the below code:
myButton.toggleClass('button-off').toggleClass('button-on');
I've tried chaining a delay(500)
between the above and a 'flip' of the above line, but that doesn't work.
I would do something like this:
$('#myButton').click(function() {
var that = $(this);
that.toggleClass('button-off button-on');
setTimeout(function() { that.toggleClass('button-off button-on'); }, 500);
});
You need to toggle both classes to switch between them.
JSBin Example
This should work:
myButton.toggleClass('button-off');
setTimeout(function() {
myButton.toggleClass('button-on');
}, 500);
精彩评论