jQuery click off element event

I have a floating div that gets displayed, and I want it to be hidden when the user clicks off the div. This would be similar to the .hover() function callback when hovering off an element. Only I want to do this for click.

I tried just setting a click event for the body, which would hide the div, but that gave unexpected results.

Anyone have ideas on how I could easily do this?


Another, possibly simpler, option would be to add a transparent div between the floating DIV and the rest of the page.

A simple click event on the transparent DIV could handle the hiding, and it would avoid the issues you are encountering with the click event.


如果您想在点击页面中的其他位置时清除div,则可以执行如下操作:

$('body').click(function(event) {
    if (!$(event.target).closest('#myDiv').length) {
        $('#myDiv').hide();
    };
});

如果你使用Jquery,你可以使用如下选择器:

$("*:not(#myDiv)").live("click", function(){
    $("#myDiv").hide();
});
链接地址: http://www.djcxy.com/p/83962.html

上一篇: 通过点击外部jQuery下拉菜单关闭

下一篇: jQuery单击元素事件