我正在尝试制作在单击按钮时打开的面板。我有按钮,我有面板。使用 click()
事件它会打开。再次按下该按钮时,它会关闭。
$('#button').click(function() {
$('#panel').toggle();
});
我想实现的是,如果用户点击除 #button
或 #panel
之外的任何地方,它也会关闭。
附言我试过这样的事情,但这不是想要的行为。
$('#button').mouseenter(function() {
$('#panel').show();
}).mouseleave(function() {
setTimeout(function() {
$('#panel').hide();
}, 2000);
});
最佳答案
$(
function(){
$("#button").click( function(){ $("#panel").toggle(); } );
$(document).click( function(e){
var elm = jQuery(e.target);
if(elm.is("#button") || elm.is("#panel") || elm.parents("#panel").length>0)return;
$("#panel").hide();
});
}
);
检查以确保点击的元素 [e.target
] 不是
- 按钮
elm.is("#button")
- 面板
elm.is("#panel")
- 面板中的任何元素
elm.parents("#panel").length>0
关于javascript - 除了打开的元素外,在任何地方都进行点击时如何关闭元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6749757/