我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
当前回答
我知道这个问题有一百万个答案,但我一直喜欢使用HTML和CSS来完成大部分工作。在这种情况下,z索引和定位。我找到的最简单的方法如下:
$(“#show trigger”).click(function(){$(“#element”).animate({width:'toggle'});$(“#外部元素”).show();});$(“#外部元素”).click(function(){$(“#element”).hide();$(“#外部元素”).hide();});#外部元件{位置:固定;宽度:100%;高度:100%;z指数:1;显示:无;}#元素{显示:无;填充:20px;背景色:#ccc;宽度:300px;z指数:2;位置:相对;}#显示触发器{填充:20px;背景色:#ccc;边距:20px自动;z指数:2;}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><div id=“outside element”></div><div id=“element”><div class=“menu item”><a href=“#1”>菜单项1</a></div><div class=“menu item”><a href=“#2”>菜单项1</a></div><div class=“menu item”><a href=“#3”>菜单项1</a></div><div class=“menu item”><a href=“#4”>菜单项1</a></div></div><div id=“show trigger”>显示菜单</div>
这创建了一个安全的环境,因为除非菜单实际打开,否则不会触发任何内容,并且z索引保护元素中的任何内容在被单击时不会产生任何错误。
此外,您不需要jQuery用传播调用覆盖所有基础,也不需要清除所有内部元素中的错误。
其他回答
Use:
var go = false;
$(document).click(function(){
if(go){
$('#divID').hide();
go = false;
}
})
$("#divID").mouseover(function(){
go = false;
});
$("#divID").mouseout(function (){
go = true;
});
$("btnID").click( function(){
if($("#divID:visible").length==1)
$("#divID").hide(); // Toggle
$("#divID").show();
});
我很惊讶没有人真正承认这一事件:
var button=document.getElementById('button');button.addEventListener('click',函数(e){e.target.style.backgroundColor=“绿色”;});button.addEventListener('焦点',函数(e){e.target.style.backgroundColor='';});<!DOCTYPE html><html><head><meta charset=“utf-8”></head><body><button id=“button”>单击</button></body></html>
要隐藏文件TreeClass(如果在其外部单击),请执行以下操作:
jQuery(document).mouseup(function (e) {
var container = $(".fileTreeClass");
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();
}
});
用纯JavaScript编写的方法
let menu = document.getElementById("menu");
document.addEventListener("click", function(){
// Hide the menus
menu.style.display = "none";
}, false);
document.getElementById("menuscontainer").addEventListener("click", function(e){
// Show the menus
menu.style.display = "block";
e.stopPropagation();
}, false);
$('#propertyType').on("click",function(e){
self.propertyTypeDialog = !self.propertyTypeDialog;
b = true;
e.stopPropagation();
console.log("input clicked");
});
$(document).on('click','body:not(#propertyType)',function (e) {
e.stopPropagation();
if(b == true) {
if ($(e.target).closest("#configuration").length == 0) {
b = false;
self.propertyTypeDialog = false;
console.log("outside clicked");
}
}
// console.log($(e.target).closest("#configuration").length);
});