Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
745 views
in Technique[技术] by (71.8m points)

jquery - mouseover while mousedown

I have a large table with with each cell being 25x25 and a div inside each one. Each div has the class of "node" and a background colour is applied to them all. I'm in the process of writing some jQuery code that will change the colour of each div when the mouse goes over it while the mouse button is down.

I currently have it so it works when I mouse over, but I only want it working when the mouse button is down aswell. I have tried many different ways to get it to work but so far I have had no look, below is my current code.

$(document).ready(function(){
  $(".node").mouseover(function(){
   $(this).css({background:"#333333"});
 });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try something like this:

$(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"});
    }
  });
});

EDIT:

You may want to do a separate mousedown on .node for individual item selections.

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

EDIT:

Here's an alternative method using bind and unbind.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...