0

我有两个元素我想将 mousemove 事件添加到 body 但我想排除这些元素。我怎样才能用 jQuery 实现这一点?

$("body").on("mousemove",function(){
    //dont run following code if mouse is on these elements
})
4

1 回答 1

1

您可以选择并缓存应排除的元素,并使用对象的 jQuery.index()方法和target属性event

var $blackList = $('#elem, #elem2, #elem3'),
       timeout = ''; 

$(document).on("mousemove", function(e) {
   // Removing last timout using ID returned by setTimeout(if any) 
   clearTimeout(timeout);  

   // Setting timeout using setTimeout function, 
   // so the handler is executed once during each specified duration   
   timeout = setTimeout(function() {
      // event.target returnes target element of the event
      // if the index of the element in jQuery collection(an array of elements) is -1
      // execute the specified code 
      if ($blackList.index(e.target) === -1) { 
          // ...
      }
   }, 50); // change the duration according to your needs
});
于 2013-09-11T15:56:35.357 回答