开发者

jquery: button mousedown state change

OK this should be easy but I can't seem to get it to work.

I have a button, when I click on it I want it to change state, but only for as long as the the button is being press开发者_如何转开发ed, like any OS native button.

So here is my code...

$('button').live('mousedown', function(){

    $(this).addClass('down');

}).live('mouseup', function(){
    $(this).removeClass('down');
});

Looks simple enough right... but this doesn't work. When you click on it, the state does change... but it stays that way... the mouseup event only works the second time you click on it.

This also happens with toggleClass and when I execute the code from the focus/blur event.

What is going on here, and how can I make it work properly?


You should consider using CSS instead, as it's much faster for display purposes than adding/removing a class via Javascript:

button:active { /* this is the mousedown pseudoelement */ }
input:focus, textarea:focus { /* this represents text input fields with focus */ }


The original solution posted by cybermotron written in jQuery works perfect for me on Chrome, Firefox and IE.

In case it does not work, perhaps setting a timeout of about 200ms on the mouseup function will improve the functionality. Not everything you want to do is a class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜