我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
当前回答
对于iPad和iPhone等触摸设备,我们可以使用以下代码:
$(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();
}
});
其他回答
投票选出最受欢迎的答案,但添加
&& (e.target != $('html').get(0)) // ignore the scrollbar
因此,单击滚动条不会隐藏目标元素。
您不需要(很多)JavaScript,只需要选择器内的:focus:
使用侧边栏:集中在显示侧边栏。在侧边栏和正文元素上设置tabindex=-1,使其可聚焦。使用sidbarEl.focus()和document.body.focus)设置侧边栏的可见性。
const menuButton=document.querySelector('.menu button');const sidebard=document.querySelector('.sidebard');menuButton.onmousedown=ev=>{ev.prpreventDefault();(边栏.包含(document.activeElement)?document.body:侧边栏).focus();};*{框大小调整:边框;}.侧边栏{位置:固定;宽度:15em;左:-15em;顶部:0;底部:0;过渡:左0.3s缓进缓出;背景色:#eef;衬垫:3em 1em;}侧边栏:焦点在{左:0;}.侧边栏:焦点{大纲:0;}.菜单按钮{位置:固定;顶部:0;左:0;填充:1em;背景色:#eef;边框:0;}正文{最大宽度:30em;边距:3em;}<body tabindex='-1'><nav class='sidebar'tabindex='-1'>提要栏内容<input-type=“text”/></nav><button class=“菜单按钮”>☰</按钮>身体内容在这里,Lorem ipsum坐amet等</body>
这是我解决这个问题的方法:
$(document).ready(function() {
$('#user-toggle').click(function(e) {
$('#user-nav').toggle();
e.stopPropagation();
});
$('body').click(function() {
$('#user-nav').hide();
});
$('#user-nav').click(function(e){
e.stopPropagation();
});
});
这对我来说非常及时:
$('body').click(function() {
// Hide the menus if visible.
});
$('#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);
});