我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
当前回答
const button=document.querySelector('button')const box=document.querySelector('.box');常量切换=事件=>{event.stopPropagation();if(!event.target.closest('.box')){console.log('单击外部');box.classList.tggle(“活动”);box.classList.contains('active')? document.addEventListener('click',切换):document.removeEventListener(“单击”,切换);}其他{console.log('单击内部');}}button.addEventListener('单击',切换);.box格式{位置:绝对;显示:无;页边空白:8px;填充:20px;背景:浅灰色;}.box激活{显示:块;}<button>切换框</button><div class=“box”><form action=“”><input-type=“text”><button type=“button”>搜索</button></form></div>
其他回答
当只有一个元素需要管理时,这里的解决方案工作得很好。然而,如果有多个元素,问题就复杂得多。e.stopPropagation()的技巧和其他所有技巧都不起作用。
我想出了一个解决方案,也许不是那么容易,但总比什么都没有好。看看:
$view.on("click", function(e) {
if(model.isActivated()) return;
var watchUnclick = function() {
rootView.one("mouseleave", function() {
$(document).one("click", function() {
model.deactivate();
});
rootView.one("mouseenter", function() {
watchUnclick();
});
});
};
watchUnclick();
model.activate();
});
$("#menuscontainer").click(function() {
$(this).focus();
});
$("#menuscontainer").blur(function(){
$(this).hide();
});
对我来说很好。
如果您正在使用“弹出窗口”等工具,则可以使用“onFocusOut”事件。
window.onload=函数(){document.getElementById(“内部div”).focus();}函数loseFocus(){警报(“在外面单击”);}#集装箱{背景色:浅蓝色;宽度:200px;高度:200px;}#内部div{背景色:浅灰色;宽度:100px;高度:100px;}<div id=“container”><input type=“text”id=“inside div”onfocusout=“loseFocus()”></div>
试试这个:
$('html').click(function(e) {
if($(e.target).parents('#menuscontainer').length == 0) {
$('#menuscontainer').hide();
}
});
https://jsfiddle.net/4cj4jxy0/
但请注意,如果单击事件无法到达html标记,则这将无法工作。(可能其他元素已停止传播())。
这对我来说非常有效!!
$('html').click(function (e) {
if (e.target.id == 'YOUR-DIV-ID') {
//do something
} else {
//do something
}
});