我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
当前回答
这是我的代码:
// Listen to every click
$('html').click(function(event) {
if ( $('#mypopupmenu').is(':visible') ) {
if (event.target.id != 'click_this_to_show_mypopupmenu') {
$('#mypopupmenu').hide();
}
}
});
// Listen to selector's clicks
$('#click_this_to_show_mypopupmenu').click(function() {
// If the menu is visible, and you clicked the selector again we need to hide
if ( $('#mypopupmenu').is(':visible') {
$('#mypopupmenu').hide();
return true;
}
// Else we need to show the popup menu
$('#mypopupmenu').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>
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();
});
注意:应该避免使用stopPropagation,因为它会破坏DOM中的正常事件流。有关更多信息,请参阅这篇CSS技巧文章。请考虑改用此方法。
将单击事件附加到关闭窗口的文档正文。将一个单独的单击事件附加到容器,以停止传播到文档正文。
$(window).click(function() {
//Hide the menus if visible
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
jQuery().ready(function(){
$('#nav').click(function (event) {
$(this).addClass('activ');
event.stopPropagation();
});
$('html').click(function () {
if( $('#nav').hasClass('activ') ){
$('#nav').removeClass('activ');
}
});
});
这是一个容器或整个文档中的解决方案。若click目标在元素之外(类为“yourClass”),则元素被隐藏。
$('yourContainer').on('click', function(e) {
if (!$(e.target).hasClass('yourClass')) {
$('.yourClass').hide();
}
});