我正在使用这段代码:
$('body').click(function() {
$('.form_wrapper').hide();
});
$('.form_wrapper').click(function(event){
event.stopPropagation();
});
这个HTML:
<div class="form_wrapper">
<a class="agree" href="javascript:;">I Agree</a>
<a class="disagree" href="javascript:;">Disagree</a>
</div>
问题是,我有链接在div和当他们不再工作时,点击。
更新解决方案为:
使用mouseenter和mouseleave代替
的悬停使用活动事件绑定
var mouseOverActiveElement = false;
$('.active').live('mouseenter', function(){
mouseOverActiveElement = true;
}).live('mouseleave', function(){
mouseOverActiveElement = false;
});
$("html").click(function(){
if (!mouseOverActiveElement) {
console.log('clicked outside active element');
}
});
根据prc322的精彩答案构建。
function hideContainerOnMouseClickOut(selector, callback) {
var args = Array.prototype.slice.call(arguments); // Save/convert arguments to array since we won't be able to access these within .on()
$(document).on("mouseup.clickOFF touchend.clickOFF", function (e) {
var container = $(selector);
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
$(document).off("mouseup.clickOFF touchend.clickOFF");
if (callback) callback.apply(this, args);
}
});
}
这增加了一些东西……
放置在带有“unlimited”参数的回调函数中
添加了对jquery的.off()的调用,与事件名称空间配对,以便在事件运行后将其从文档中解绑定。
包括触摸端移动功能
我希望这能帮助到一些人!
摘自https://sdtuts.com/click-on-not-specified-element/
现场演示http://demos.sdtuts.com/click-on-specified-element
$(document).ready(function () {
var is_specified_clicked;
$(".specified_element").click(function () {
is_specified_clicked = true;
setTimeout(function () {
is_specified_clicked = false;
}, 200);
})
$("*").click(function () {
if (is_specified_clicked == true) {
//WRITE CODE HERE FOR CLICKED ON OTHER ELEMENTS
$(".event_result").text("you were clicked on specified element");
} else {
//WRITE CODE HERE FOR SPECIFIED ELEMENT CLICKED
$(".event_result").text("you were clicked not on specified element");
}
})
})