jQuery:如何检测鼠标点击位置是否在 div 之外
jQuery: How to detect if mouse click location is outside of a div
我有这段代码可以检测网站上的任何鼠标点击:
$(document).mousedown(function() {
console.log("you clicked somewhere.");
});
如何让它只在点击位置在 #specificDiv
之外时触发操作?
您可以使用:
$(document).mousedown(function(event) {
var specificDiv= $("#specificDiv");
if (specificDiv.is(event.target))
console.log("you clicked specificDiv.");
});
$(document).mousedown(function() {
if($(this).closest('#specificDiv').length == 0){
}
});
使用事件对象的target
属性。
target
指向生成事件的元素
var myDiv = $("#myDiv");
$(document).mousedown(function(ev) {
if(myDiv.is(ev.target)){
console.log("you clicked on myDiv.");
}else{
console.log("you clicked somewhere.");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv" style="height:100px; width:100px; background-color:#00FF00;" ></div>
这应该对您有帮助:
$(document).mousedown(function (ev) {
var $target = $(ev.target);
var $specificDiv = $target.closest('#specificDiv');
if (!$specificDiv || !$specificDiv.length) {
// clicked location is outside
}
});
$('#your_div').mousedown(function(e){
e.stopPropagation(); //Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
});
$(document).mousedown(function(e){
console.log("you clicked somewhere.");
});
我有这段代码可以检测网站上的任何鼠标点击:
$(document).mousedown(function() {
console.log("you clicked somewhere.");
});
如何让它只在点击位置在 #specificDiv
之外时触发操作?
您可以使用:
$(document).mousedown(function(event) {
var specificDiv= $("#specificDiv");
if (specificDiv.is(event.target))
console.log("you clicked specificDiv.");
});
$(document).mousedown(function() {
if($(this).closest('#specificDiv').length == 0){
}
});
使用事件对象的target
属性。
target
指向生成事件的元素
var myDiv = $("#myDiv");
$(document).mousedown(function(ev) {
if(myDiv.is(ev.target)){
console.log("you clicked on myDiv.");
}else{
console.log("you clicked somewhere.");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv" style="height:100px; width:100px; background-color:#00FF00;" ></div>
这应该对您有帮助:
$(document).mousedown(function (ev) {
var $target = $(ev.target);
var $specificDiv = $target.closest('#specificDiv');
if (!$specificDiv || !$specificDiv.length) {
// clicked location is outside
}
});
$('#your_div').mousedown(function(e){
e.stopPropagation(); //Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
});
$(document).mousedown(function(e){
console.log("you clicked somewhere.");
});