Mouseup and Mousedown

狂风中的少年 提交于 2019-12-08 06:54:41

问题


So I want the buttons to change style when mouse is down, and return to previous when it goes up. I have this code:

$('#divMenu > #menu li a').mousedown(function(){
  $(this).css({
  'font-size': '25px',  
  'color': 'red'     
  });               
}).mouseup(function(){
  $(this).css({
  'font-size': '30px',  
  'color': 'black'     
  });               
});

The problem is, that when I have mouse down, but take it away of my object and not release immediately, font size and color stays 25px and red. What should I do to pass that?

EDIT: JsFiddle here: http://jsfiddle.net/h64Uz/


回答1:


You need to use a mouseout as well.

$('#divMenu > #menu li a').mousedown(function(){
  $(this).css({
  'font-size': '25px',  
  'color': 'red'     
  });               
}).mouseup(function(){
  $(this).css({
  'font-size': '30px',  
  'color': 'black'     
  });               
}).mouseout(function(){
  $(this).css({
  'font-size': '30px',  
  'color': 'black'     
  });               
});

Your event code sets the css when the mouse is clicked. Once you move away it can't register a mouseup. But on leaving it will register a mouseout event.




回答2:


jQuery has a mouseleave() event you can use to supplement the existing code:




回答3:


This should work (assuming you are using jQuery version 1.7 or above):

$('#divMenu > #menu li a').on("mousedown", function () {
  $(this).css({
    'font-size': '25px',
      'color': 'red'
  });
}).on("mouseup mouseout", function () {
  $(this).css({
    'font-size': '30px',
      'color': 'black'
  });
});


来源:https://stackoverflow.com/questions/14207927/mouseup-and-mousedown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!