鼠标hover时mousedown

我有一个大桌子,每个单元格为25×25,每个单元格内有一个div。 每个div都有“node”类,并且背景颜色都应用于它们。 我正在编写一些jQuery代码,当鼠标停在鼠标按钮时,它将改变每个div的颜色。

我现在拥有它,所以当我鼠标hover时它可以工作,但我只希望它在鼠标按钮关闭时工作。 我已经尝试了很多不同的方法让它工作,但到目前为止我没有看,下面是我目前的代码。

$(document).ready(function(){ $(".node").mouseover(function(){ $(this).css({background:"#333333"}); }); }); 

尝试这样的事情:

 $(document).ready(function(){ var isDown = false; // Tracks status of mouse button $(document).mousedown(function() { isDown = true; // When mouse goes down, set isDown to true }) .mouseup(function() { isDown = false; // When mouse goes up, set isDown to false }); $(".node").mouseover(function(){ if(isDown) { // Only change css if mouse is down $(this).css({background:"#333333"}); } }); }); 

编辑:

您可能希望在.node上单独进行mousedown以进行单个项目选择。

  $('.node').mousedown(function() { $(this).css({background:"#333333"}); }); 

编辑:

这是使用bindunbind的替代方法。

  $(document).mousedown(function() { $(".node").bind('mouseover',function(){ $(this).css({background:"#333333"}); }); }) .mouseup(function() { $(".node").unbind('mouseover'); }); $('.node').mousedown(function() { $(this).css({background:"#333333"}); }); 

好吧,如果鼠标按钮关闭,则更改背景,如果上升,则更改回…

 $(".node").mouseup(function(){ $(this).css({background:'#cccccc'}); }).mousedown(function(){ $(this).css({background:'#333333'}); }); 

这是你在找什么?

在http://api.jquery.com/mousedown/了解更多信息