开发者

Toggle element class with jQuery?

开发者 https://www.devze.com 2023-04-03 20:39 出处:网络
I\'ve been having some problem with this code $(\"#click\").bind(\'mousedown mouseup mouseover\', function(e) {

I've been having some problem with this code

$("#click").bind('mousedown mouseup mouseover', function(e) {
    if(e.type === 'mouseover'){
        $(this).addClass('open'); //works!
    }
    if(e.type === 'mousedown'){
       $(this).removeClass().addClass('closed'); //works!
    }
    if(e.type === 'mouseup'){
       $(this).removeClass().addClass('open');
       // The above line doesn't work :(
    }
});

Demo here This code only works for mouseover, mousedown and NOT for mouseup. When I uncomment $(this).removeClass().addClass('open'); the mousedown event stops triggering as well.

Anybody have an idea what the proble开发者_如何转开发m may be?


Fixed: http://jsfiddle.net/U544t/2/

You need to remove the class you don't want, then add the class you do. You were ending up with the div having both open and closed, thus it was only showing the closed icon.


Unless I'm missing something, it seems you could do this a bit more efficiently with toggleClass() instead of doing all the add/remove yourself. And you probably don't need two classes, just a default state, and the .open class to trigger the active upon toggling.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号