我有两个元素我想将mousemove事件添加到body但我想要排除这些元素。我怎样才能用jQuery实现这个目标?
$("body").on("mousemove",function(){
//dont run following code if mouse is on these elements
})
答案 0 :(得分:1)
您可以选择并缓存应排除的元素,并使用.index()
对象的jQuery 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
});