// Detect the click anywhere other than the overlay element to close it.Y.one(document).on('click', function (e) {if (e.target.ancestor('#overlay') === null && e.target.get('id') != 'show' && overlay.get('visible') == true) {overlay.hide();}});
$('#menuscontainer').click(function(event) {//your code that shows the menus fully
//now set up an event listener so that clicking anywhere outside will close the menu$('html').click(function(event) {//check up the tree of the click target to check whether user has clicked outside of menuif ($(event.target).parents('#menuscontainer').length==0) {// your code to hide menu
//this event listener has done its job so we can unbind it.$(this).unbind(event);}
})});
// 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 hideif ( $('#mypopupmenu').is(':visible') {$('#mypopupmenu').hide();return true;}
// Else we need to show the popup menu$('#mypopupmenu').show();});
$(document).click(function(e){if ($(e.target).closest("#menuscontainer").length == 0) {// .closest can help you determine if the element// or one of its ancestors is #menuscontainerconsole.log("hide");}});
<a id='theButton' href="#">Toggle the menu</a><br/><div id='theMenu'>I should be toggled when the above menu is clicked,and hidden when user clicks outside.</div>
<script>$('#theButton').click(function(){$('#theMenu').slideDown();});$("#theMenu").dClickOutside({ ignoreList: $("#theButton") }, function(clickedObj){$(this).slideUp();});</script>
$('html').click(function() {// Hide the menus if visible});
$('#menucontainer').click(function(event){event.stopPropagation();});
它防止ruby on rails UJS驱动程序无法正常工作。例如,link_to 'click', '/url', :method => :delete将无法工作。
这可能是一个解决方法:
$('html').click(function() {// Hide the menus if visible});
$('#menucontainer').click(function(event){if (!$(event.target).data('method')) {event.stopPropagation();}});
$("*").not($("#menuscontainer")).bind("click.OutsideMenus", function (){// hide the menus
//then remove all of the handlers$("*").unbind(".OutsideMenus");});
$("#menuscontainer").bind("click.OutsideMenus", function (event){event.stopPropagation();});
$(document).on("click.menu-outside", function(event){// Test if target and it's parent aren't #menuscontainer// That means the click event occur on other branch of document treeif(!$(event.target).parents().andSelf().is("#menuscontainer")){// Click outisde #menuscontainer// Hide the menus (but test if menus aren't already hidden)}});
window.autoCloseQueue = {}
$(document).click(function(event) {for (id in autoCloseQueue){var element = autoCloseQueue[id];if ( ($(e.target).parents('#' + id).length) > 0) { // This is a click on the element (or its child element)console.log('This is a click on an element (or its child element) with id: ' + id);if (typeof element.onPress == 'function') element.onPress(event, id);} else { //This is a click outside the elementconsole.log('This is a click outside the element with id: ' + id);if (typeof element.onOutsidePress == 'function') element.onOutsidePress(event, id); //call the outside callbackdelete autoCloseQueue[id]; //remove the element from the queue}}});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><li id="menu"><a></a></li><ul id="nav"><!--Nav will toggle when you Click on Menu(it can be an icon in this example)--><li class="page"><a>Page1</a></li><li class="page"><a>Page2</a></li><li class="page"><a>Page3</a></li><li class="page"><a>Page4</a></li></ul>
var $menu = $('#menucontainer');$(document).on('click', function (e) {
// If element is opened and click target is outside it, hide itif ($menu.is(':visible') && !$menu.is(e.target) && !$menu.has(e.target).length) {$menu.hide();}});
$(document).on('touchstart', function (event) {var container = $("YOUR CONTAINER SELECTOR");
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();}});
var flag = "1";$('#menucontainer').click(function(event){flag = "0"; // flag 0 means click happened in the area where we should not do any action});
$('html').click(function() {if(flag != "0"){// Hide the menus if visible}else {flag = "1";}});
解决方案2
只有一个简单的if条件:
$(document).on('click', function(event){var container = $("#menucontainer");if (!container.is(event.target) && // If the target of the click isn't the container...container.has(event.target).length === 0) // ... nor a descendant of the container{// Do whatever you want to do when click is outside the element}});
<a href="javascript:void(0)" id="toggle">Toggle Hidden Div</a><div id="hidden" style="display: none;">This content is normally hidden. click anywhere other than this content to make me disappear</div>
// HIDE SEARCH BOX IF CLICKING OUTSIDE$(document).click(function(event){// IF NOT CLICKING THE SEARCH BOX OR ITS CONTENTS OR SEARCH ICONif ($("#search-holder").is(":visible") && !$(event.target).is("#search-holder *, #search")) {$("#search-holder").fadeOut('fast');$("#search").removeClass('active');}});
$('.target-element').outsideClick(function(event){//code that fires when user clicks outside the element//event = the click event//$(this) = the '.target-element' that is firing this function}, '.excluded-element')
它的代码:
(function($) {
//when the user hits the escape key, it will trigger all outsideClick functions$(document).on("keyup", function (e) {if (e.which == 27) $('body').click(); //escape key});
//The actual plugin$.fn.outsideClick = function(callback, exclusions) {var subject = this;
//test if exclusions have been setvar hasExclusions = typeof exclusions !== 'undefined';
//switches click event with touch event if on a touch devicevar ClickOrTouchEvent = "ontouchend" in document ? "touchend" : "click";
$('body').on(ClickOrTouchEvent, function(event) {//click target does not contain subject as a parentvar clickedOutside = !$(event.target).closest(subject).length;
//click target was on one of the excluded elementsvar clickedExclusion = $(event.target).closest(exclusions).length;
var testSuccessful;
if (hasExclusions) {testSuccessful = clickedOutside && !clickedExclusion;} else {testSuccessful = clickedOutside;}
if(testSuccessful) {callback.call(subject, event);}});
return this;};
}(jQuery));
<script>//The good thing about this solution is it doesn't stop event propagation.
var clickFlag = 0;$('body').on('click', function () {if(clickFlag == 0) {console.log('hide element here');/* Hide element here */}else {clickFlag=0;}});$('body').on('click','#testDiv', function (event) {clickFlag = 1;console.log('showed the element');/* Show the element */});</script>
第二种解决方案
<script>$('body').on('click', function(e) {if($(e.target).closest('#testDiv').length == 0) {/* Hide dropdown here */}});</script>
$(document).mouseup(function (e){var container = $("YOUR SELECTOR"); // Give you class or ID
if (!container.is(e.target) && // If the target of the click is not the desired div or sectioncontainer.has(e.target).length === 0) // ... nor a descendant-child of the container{container.hide();}});
div {float: left;}
ul {padding: 0;position: relative;}ul li {padding: 5px 25px 5px 10px;border: 1px solid silver;cursor: pointer;list-style: none;margin-top: -1px;white-space: nowrap;}ul li ul:before {margin-right: -20px;position: absolute;top: -17px;right: 0;content: "\25BC";}ul li ul li {visibility: hidden;height: 0;padding-top: 0;padding-bottom: 0;border-width: 0 0 1px 0;}ul li ul li:last-child {border: none;}ul li ul.active:before {content: "\25B2";}ul li ul.active li {display: list-item;visibility: visible;height: inherit;padding: 5px 25px 5px 10px;}
$('a').on('click', function () {$(this.hash).toggleClass('active').focus();});
$('div').on('focusout', function () {$(this).removeClass('active');});
div {display: none;}.active {display: block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><a href="#example">Example</a><div id="example" tabindex="-1">Lorem ipsum <a href="http://example.com">dolor</a> sit amet.</div>
$('.submenu').on({focusout: function (e) {$(this).data('submenuTimer', setTimeout(function () {$(this).removeClass('submenu--active');}.bind(this), 0));},focusin: function (e) {clearTimeout($(this).data('submenuTimer'));}});
$('a').on('click', function () {$(this.hash).toggleClass('active').focus();});
$('div').on({focusout: function () {$(this).data('timer', setTimeout(function () {$(this).removeClass('active');}.bind(this), 0));},focusin: function () {clearTimeout($(this).data('timer'));}});
div {display: none;}.active {display: block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><a href="#example">Example</a><div id="example" tabindex="-1">Lorem ipsum <a href="http://example.com">dolor</a> sit amet.</div>
$('a').on({focusout: function () {$(this.hash).data('timer', setTimeout(function () {$(this.hash).removeClass('active');}.bind(this), 0));},focusin: function () {clearTimeout($(this.hash).data('timer'));}});
$('a').on('click', function () {$(this.hash).toggleClass('active').focus();});
$('div').on({focusout: function () {$(this).data('timer', setTimeout(function () {$(this).removeClass('active');}.bind(this), 0));},focusin: function () {clearTimeout($(this).data('timer'));}});
$('a').on({focusout: function () {$(this.hash).data('timer', setTimeout(function () {$(this.hash).removeClass('active');}.bind(this), 0));},focusin: function () {clearTimeout($(this.hash).data('timer'));}});
div {display: none;}.active {display: block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><a href="#example">Example</a><div id="example" tabindex="-1">Lorem ipsum <a href="http://example.com">dolor</a> sit amet.</div>
keydown: function (e) {if (e.which === 27) {$(this).removeClass('active');e.preventDefault();}}
$('a').on('click', function () {$(this.hash).toggleClass('active').focus();});
$('div').on({focusout: function () {$(this).data('timer', setTimeout(function () {$(this).removeClass('active');}.bind(this), 0));},focusin: function () {clearTimeout($(this).data('timer'));},keydown: function (e) {if (e.which === 27) {$(this).removeClass('active');e.preventDefault();}}});
$('a').on({focusout: function () {$(this.hash).data('timer', setTimeout(function () {$(this.hash).removeClass('active');}.bind(this), 0));},focusin: function () {clearTimeout($(this.hash).data('timer'));}});
div {display: none;}.active {display: block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><a href="#example">Example</a><div id="example" tabindex="-1">Lorem ipsum <a href="http://example.com">dolor</a> sit amet.</div>
如果您知道对话框中有可聚焦的元素,则不需要直接对话框。如果您正在构建菜单,则可以对焦第一个菜单项。
click: function (e) {$(this.hash).toggleClass('submenu--active').find('a:first').focus();e.preventDefault();}
$('.menu__link').on({click: function (e) {$(this.hash).toggleClass('submenu--active').find('a:first').focus();e.preventDefault();},focusout: function () {$(this.hash).data('submenuTimer', setTimeout(function () {$(this.hash).removeClass('submenu--active');}.bind(this), 0));},focusin: function () {clearTimeout($(this.hash).data('submenuTimer'));}});
$('.submenu').on({focusout: function () {$(this).data('submenuTimer', setTimeout(function () {$(this).removeClass('submenu--active');}.bind(this), 0));},focusin: function () {clearTimeout($(this).data('submenuTimer'));},keydown: function (e) {if (e.which === 27) {$(this).removeClass('submenu--active');e.preventDefault();}}});
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();}});
$(".menu_link").click(function(){// show menu code});
$(".menu_link").mouseleave(function(){//hide menu code, you may add a timer for 3 seconds before code to be run});
var isMenuClick = false;var menu = document.getElementById('menuscontainer');document.addEventListener('click',()=>{if(!isMenuClick){//Hide the menu here}//Reset isMenuClickisMenuClick = false;})menu.addEventListener('click',()=>{isMenuClick = true;})
document.body.onclick = function() { undisp_menu(); };var menu_on = 0;
function menu_trigger(event){
if (menu_on == 0){// otherwise u will call the undisp on body when// click on the buttonevent.stopPropagation();
disp_menu();}
else{undisp_menu();}
}
function disp_menu(){
menu_on = 1;var e = document.getElementsByClassName("menu")[0];e.className = "menu on";
}
function undisp_menu(){
menu_on = 0;var e = document.getElementsByClassName("menu")[0];e.className = "menu";
}
jQuery(document).click(function(e) {var target = e.target; //target div recordedif (!jQuery(target).is('#tobehide') ) {jQuery(this).fadeOut(); //if the click element is not the above id will hide}})
下面找到超文本标记语言代码
<div class="main-container"><div> Hello I am the title</div><div class="tobehide">I will hide when you click outside of me</div></div>
/* just to make it good looking. you don't need this */#myTarget {margin: 50px auto;width: 500px;height: 500px;background: gray;border: 10px solid black;}
dialog = document.getElementById("dialogElement")
dialog.addEventListener("focusout", function (event) {if (// we are still inside the dialog so don't closedialog.contains(event.relatedTarget) ||// we have switched to another tab so probably don't want to close!document.hasFocus()) {return;}dialog.close(); // or whatever logic you want to use to close});
let menu = document.getElementById("menu");
document.addEventListener("click", function(){// Hide the menusmenu.style.display = "none";}, false);
document.getElementById("menuscontainer").addEventListener("click", function(e){// Show the menusmenu.style.display = "block";e.stopPropagation();}, false);