나는 어떤 메뉴를 클릭하면 HTML 가르켜 fy05 머리에 있는 이러한 메뉴. # 39 을 클릭하면 위부의 menus& 이러한 요소를 숨기기 싶다. 영역.
Jquery 는 이 같은 일이 발생할 수 있는?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
>. 참고: 때문에 브레이크를 사용하여 스토피번트프로파가티온 () '가' 정상적인 이벤트 흐름 또한 DOM 생각하신거야 피해야 합니다. 이 문서 에서 자세한 내용을 참조. 사용을 고려해보십시오 [이 방법] (https://stackoverflow.com/a/3028037/561309) 를 대신
Click 이벤트에 부착합니다 바디입니다 문서에 대한 어떤 창이 닫힙니다. 전파할 수 있는 별도의 부착합니다 click 이벤트에 컨테이너입니다 정지점으로 문서에 대한 바디입니다.
$(window).click(function() {
//Hide the menus if visible
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
그렇지 않을 경우 '와' # 메누콘타이너 밖에서 클릭한 다음 이 사실을 숨기고 요소가 됩니다.
$(document).click(function(event) {
$target = $(event.target);
if(!$target.closest('#menucontainer').length &&
$('#menucontainer').is(":visible")) {
$('#menucontainer').hide();
}
});
또한 이벤트 리스너에 후 클린업합니다 생략하려면 계획이라면 메뉴 및 매핑하려는 정지점을 이벤트를 수신하는. 이 기능은 그대로 유지하면서 리스너에) 에 '를 새로 작성한 문서를 다른 미디어만을 클린업합니다 리스너에'. 함께 ES2015 문법:
export function hideOnClickOutside(selector) {
const outsideClickListener = (event) => {
$target = $(event.target);
if (!$target.closest(selector).length && $(selector).is(':visible')) {
$(selector).hide();
removeClickListener();
}
}
const removeClickListener = () => {
document.removeEventListener('click', outsideClickListener)
}
document.addEventListener('click', outsideClickListener)
}
function hideOnClickOutside(element) {
const outsideClickListener = event => {
if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null
element.style.display = 'none'
removeClickListener()
}
}
const removeClickListener = () => {
document.removeEventListener('click', outsideClickListener)
}
document.addEventListener('click', outsideClickListener)
}
const isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ) // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js
하지만 '엘레망스클로스트 () 에서 사용할 수 있다' 는 현재 모든 주요 브라우저 () 는 W3C 에서 조금 다른 한 버전을 포함한다). 폴리필스 여기에서 찾을 수 있습니다. 엘레망스클로스트 ()
>. 클릭 한 요소를 바깥쪽인지가 탐지합니다 방법?
이처럼 이 질문은 인기 계시한하나님께 믿을 수 있다는 답변을 너무 복잡하다. 거의 8 년, 수십 개의 답변이 많이 나는 그동안 성실하게 잘 못하지 리틀이에요 액세서빌러티를 주어졌다.
>. # 39 을 클릭하면 위부의 menus& 이러한 요소를 숨기기 싶다. 영역.
이것은 훌륭한 원인 및 는 실제 배정됩니다. 제목이 question& 어떤 대답을 할 수 있는 것처럼, mdash;; mdash; map_layer address& 가장 불행한 레드 허링.
그래서 let& 말할께 # 39 에 질문.
>. 이를 통해 사용자가 대화 닫으십시오 완료될 때 어떻게 해야 할까요?
이 목표는. 이제 우리가 할 수 있는 '' 이벤트 및 죄송합니다. 바인딩해야 저리스핀리셰트비스타디아로그 isn& 바인딩하면 # 39, t so 쉽습니다.
그래서 어떻게 탐지합니다 사용하여 사용자가 완료된 대화?
좋은 start 는 왼쪽 대화상자는 여부를 결정하는 데 초점을 맞추고 있다.
'포쿠사우스' # 39 의 jquery& 좋았소 할 것입니다. # 39 can& 사용할 경우, jQuery 관심용 중에 사용할 수 있습니다 't' 흐림의 캡처을 단계:
element.addEventListener('blur', ..., true);
// use capture: ^^^^
또한 많은 대화상자의 you& # 39, ll 수 있도록 하는 컨테이너입니다 초점을 맞춥니다. ',' 받을 수 있도록 추가 tabindex = " - 1" 대화상자의 데 영향을 주지 않고 무중단으로 그렇지 않으면 탭 흐름.
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
$('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>
끝 - < 스니핏 >;!
함께 뛸 경우 그 분) 보다 빠르게 합니다 데모를 시작하는 것을 문제.
첫 번째는 해당 링크가 대화상자의 isn& # 39, t 클릭가능 (b). 시도중입니다 정보기술 (it) 또는 탭을 클릭하여 대화상자의 닫기와 상호 작용 수행되는지 전에 붕괴될 것이라고 말했다. 이 때문에 '있다' 는 '이벤트' 포커신 안쪽 요소점 트리거되는 포쿠사우스 이벤트 트리거하기 전에 다시.
이 문제를 해결하려면 해당 이벤트에 대한 루프지 대기열은 상태 변경 이 작업을 수행할 수 있습니다 (.) '또는', '세이마드리아티 사용하여 setTimeout (., 0)', '# 39 브라우저에 대한 don& 있는 t 지원 세이마드리아티'. '후속' 포커신 의해 한 번 대기됨 선택취소됩니다 수 있습니다.
$('.submenu').on({
focusout: function (e) {
$(this).data('submenuTimer', setTimeout(function () {
$(this).removeClass('submenu--active');
}.bind(this), 0));
},
focusin: function (e) {
clearTimeout($(this).data('submenuTimer'));
}
});
<! - begin 스니핏: js 숨기십시오: 진정한 콘솔: 진정한 바벨. > 거짓값 -;
$('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>
끝 - < 스니핏 >;!
두 번째 문제는 해당 링크를 사용할 때, t # 39 won& 대화상자는 닫으십시오 눌려졌습니다 다시. 이 때문에 유실됩니다 대화상자는 두고, 그 이후에는 다시 대화상자의 트리거합니다 트리거합니다 비헤이비어를 닫으십시오 링크를 클릭합니다.
지난해와 비슷한 문제를 집중 스테이드 관리되어야 합니다. # 39 점을 감안할 때 상태 변경, s just a matter of 취급료 포커스, 이미 대기됨 it& 대화상자의 이벤트별로 트리거합니다:
$('a').on({
focusout: function () {
$(this.hash).data('timer', setTimeout(function () {
$(this.hash).removeClass('active');
}.bind(this), 0));
},
focusin: function () {
clearTimeout($(this.hash).data('timer'));
}
});
<! - begin 스니핏: js 숨기십시오: 진정한 콘솔: 진정한 바벨. > 거짓값 -;
$('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>
끝 - < 스니핏 >;!
많은 경우, 주 (州) 에 의해 수행된 취급료 조교하실 돌아보 there& # 39 더 단순화하도록 사용자 경험을 할 수 있습니다.
종종 이 have" ", 반갑다. 그러나 일반적인 모달 피쳐에는 it& # 39 에 있는 경우, 또는 어떤 종류의 작업자쪽에서 < kbd> Esc< /kbd>, 팝업;; 키는 닫으십시오 초과됩니다.
keydown: function (e) {
if (e.which === 27) {
$(this).removeClass('active');
e.preventDefault();
}
}
<! - begin 스니핏: js 숨기십시오: 진정한 콘솔: 진정한 바벨. > 거짓값 -;
$('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>
끝 - < 스니핏 >;!
알고 있다면 당신은 포커스 요소는 대화상자의 너회가 won& # 39, t need to focus 대화상자는 직접. # 39 you& 경우, 메뉴, re 건물 대신 첫 번째 메뉴 항목을 두고 수 있습니다.
click: function (e) {
$(this.hash)
.toggleClass('submenu--active')
.find('a:first')
.focus();
e.preventDefault();
}
<! - begin 스니핏: js 숨기십시오: 진정한 콘솔: 진정한 바벨. > 거짓값 -;
$('.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();
}
}
});
.menu {
list-style: none;
margin: 0;
padding: 0;
}
.menu:after {
clear: both;
content: '';
display: table;
}
.menu__item {
float: left;
position: relative;
}
.menu__link {
background-color: lightblue;
color: black;
display: block;
padding: 0.5em 1em;
text-decoration: none;
}
.menu__link:hover,
.menu__link:focus {
background-color: black;
color: lightblue;
}
.submenu {
border: 1px solid black;
display: none;
left: 0;
list-style: none;
margin: 0;
padding: 0;
position: absolute;
top: 100%;
}
.submenu--active {
display: block;
}
.submenu__item {
width: 150px;
}
.submenu__link {
background-color: lightblue;
color: black;
display: block;
padding: 0.5em 1em;
text-decoration: none;
}
.submenu__link:hover,
.submenu__link:focus {
background-color: black;
color: lightblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
<li class="menu__item">
<a class="menu__link" href="#menu-1">Menu 1</a>
<ul class="submenu" id="menu-1" tabindex="-1">
<li class="submenu__item"><a class="submenu__link" href="http://example.com/#1">Example 1</a></li>
<li class="submenu__item"><a class="submenu__link" href="http://example.com/#2">Example 2</a></li>
<li class="submenu__item"><a class="submenu__link" href="http://example.com/#3">Example 3</a></li>
<li class="submenu__item"><a class="submenu__link" href="http://example.com/#4">Example 4</a></li>
</ul>
</li>
<li class="menu__item">
<a class="menu__link" href="#menu-2">Menu 2</a>
<ul class="submenu" id="menu-2" tabindex="-1">
<li class="submenu__item"><a class="submenu__link" href="http://example.com/#1">Example 1</a></li>
<li class="submenu__item"><a class="submenu__link" href="http://example.com/#2">Example 2</a></li>
<li class="submenu__item"><a class="submenu__link" href="http://example.com/#3">Example 3</a></li>
<li class="submenu__item"><a class="submenu__link" href="http://example.com/#4">Example 4</a></li>
</ul>
</li>
</ul>
lorem ipsum <a href="http://example.com/">dolor</a> sit amet.
끝 - < 스니핏 >;!
이 질문에 대한 기본 자동화합니다 용이하게 할 수 있는 이 기능에 대한 키보드와 마우스 지원 아니라 이미 꽤 널찍한 I& it& # 39 에 대한 모든 논의는 피할 것 # 39 m, 아리아 (aria) 인 역할 및 속성, 그러나 나는 그 어떤 역할에 대한 자세한 내용은 매우 추천합니까 구현자 권장하십시오 사양 및 기타 적절한 속성 사용해야 합니다.
나는 내가 애플리케이션과는 Eran& 비슷하게 작동하는 # 39 의 acrobatconnectcentral. 아니했노라 부착합니다 몸에 클릭 이벤트 때 내가 메뉴를 엽니다. 좀 다음과 같습니다.
$('#menucontainer').click(function(event) {
$('html').one('click',function() {
// Hide the menus
});
event.stopPropagation();
});
[JQuery& # 39 의 'one ()' 기능을] 에 대한 자세한 내용은 1
나는 세 가지 작업 후 연구 com/downloads/global/corporate/iar/esg_prosupport. 솔루션 (내가 지은 페이지 링크 참조)
<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>
<script>
var specifiedElement = document.getElementById('testDiv');
document.addEventListener('click', function(event) {
var isClickInside = specifiedElement.contains(event.target);
if (isClickInside) {
console.log('You clicked inside')
}
else {
console.log('You clicked outside')
}
});
</script>
이제 용 플러그인을 다음과 같이 밝혔다: 바깥쪽인지가 이벤트 (블로그 포스트)
쓸 만한 답을 찾을 수 없는 나를 프롬프트될 위 이 블로그 포스트 다른 날. 보다 현학적, 여러 가지 정보 를 기록하십시오:
또 다른 예를 포스터 기도하였나니 정보, 특히 많아 경우 요소점 틀렸다니까 디스플레이하여 (이 경우 메뉴) 는 인터랙티브 요소.
$('#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 menu
if ($(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);
}
})
});
간편하게 상황이다.
$(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 section
container.has(e.target).length === 0) // ... nor a descendant-child of the container
{
container.hide();
}
});
위의 스크립트는 div "만약 '이벤트' 를 div 숨김니다 '외부의 트리거됩니다.
다음 블로그 자세한 정보를 확인할 수 있습니다. http://www.codecanal.com/detect-click-outside-div-using-javascript/
가질 수 있는 일부 사용하는 대신, 그냥 단순한 플래깅 가변으로 정의하십시오 때는기대어 저하됨 에번트리스토파로파가티온 () '' 한 경우 추가 조건. 내가 이 및 제대로 작동되었던 삭제의 부작용 없이 테스트되었습니다 스토프로파가티온:
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";
}
});
부트해 경우 단순 '' 조건:
$(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
}
});
var $menuscontainer = ...;
$('#trigger').click(function() {
$menuscontainer.show();
$('body').click(function(event) {
var $target = $(event.target);
if ($target.parents('#menuscontainer').length == 0) {
$menuscontainer.hide();
}
});
});
논리는: # 매너스콘타이너 '때' 를 '# 매너스콘타이너 감춰집니다 처리기에서 표시됨을 바인딩한 몸에 있는 경우에만' 대상 () 의 클릭), t # 39 isn& 하위여야 것이다.
변형으로 취급된다.
var $menu = $('#menucontainer');
$(document).on('click', function (e) {
// If element is opened and click target is outside it, hide it
if ($menu.is(':visible') && !$menu.is(e.target) && !$menu.has(e.target).length) {
$menu.hide();
}
});
이 문제가 없다 중지 전파 이벤트 는 여러 메뉴를 클릭하면 같은 페이지에서 두 번째 메뉴 및 더 열려 있는 동안 첫 번째 열린 첫 스토프로파가티온 솔루션이므로 떠날 예정이다.
내가 찾은 일부 캘리저 플러그인에는 이 방법을 포함한다.
function ClickOutsideCheck(e)
{
var el = e.target;
var popup = $('.popup:visible')[0];
if (popup==undefined)
return true;
while (true){
if (el == popup ) {
return true;
} else if (el == document) {
$(".popup").hide();
return false;
} else {
el = $(el).parent()[0];
}
}
};
$(document).bind('mousedown.popup', ClickOutsideCheck);
이번 행사는 불렀으매 프랑드패스 속성, 이는 모든 요소의 " 목록니다 order" 진단트리에서, 조상이 정적임 오더할 있다. 특정 지점의 재생하느뇨 여부를 확인할 수 있는 이벤트 중 하나가 바로 확인할 수 있는 경로를 특정 DOM DOM 요소이거나 하위 요소. 논리적으로 여러 요소를 확인하는 데 사용될 수도 있다 '또는' ing '일부' 기능을 통해 요소 체크인합니다.
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
$("body").click(function() {
target = document.getElementById("main");
flag = event.path.some(function(el, i, arr) {
return (el == target)
})
if (flag) {
console.log("Inside")
} else {
console.log("Outside")
}
});
#main {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<ul>
<li>Test-Main</li>
<li>Test-Main</li>
<li>Test-Main</li>
<li>Test-Main</li>
<li>Test-Main</li>
</ul>
</div>
<div id="main2">
Outside Main
</div>
끝 - < 스니핏 >;!
그래서 케이스 한다
$("body").click(function() {
target = $("#menuscontainer")[0];
flag = event.path.some(function(el, i, arr) {
return (el == target)
});
if (!flag) {
// Hide the menus
}
});
다음은 향후 바닐라 JavaScript 솔루션이므로 있다.
(function () {
"use strict";
var hidden = document.getElementById('hidden');
document.addEventListener('click', function (e) {
if (e.target.id == 'toggle' || (hidden.style.display != 'none' && !hidden.contains(e.target))) hidden.style.display = hidden.style.display == 'none' ? 'block' : 'none';
}, false);
})();
<! - begin 스니핏: js 숨기십시오: 참 - >.
(function () {
"use strict";
var hidden = document.getElementById('hidden');
document.addEventListener('click', function (e) {
if (e.target.id == 'toggle' || (hidden.style.display != 'none' && !hidden.contains(e.target))) hidden.style.display = hidden.style.display == 'none' ? 'block' : 'none';
}, false);
})();
<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>
끝 - < 스니핏 >;!
누르면 여러 개 있을 경우 이 같은 일이 될 것 같은 페이지에서 사용할 수 있습니다.
<! - begin 스니핏: js 숨기십시오: > 거짓값 -;
(function () {
"use strict";
var hiddenItems = document.getElementsByClassName('hidden'), hidden;
document.addEventListener('click', function (e) {
for (var i = 0; hidden = hiddenItems[i]; i++) {
if (!hidden.contains(e.target) && hidden.style.display != 'none')
hidden.style.display = 'none';
}
if (e.target.getAttribute('data-toggle')) {
var toggle = document.querySelector(e.target.getAttribute('data-toggle'));
toggle.style.display = toggle.style.display == 'none' ? 'block' : 'none';
}
}, false);
})();
<a href="javascript:void(0)" data-toggle="#hidden1">Toggle Hidden Div</a>
<div class="hidden" id="hidden1" style="display: none;" data-hidden="true">This content is normally hidden</div>
<a href="javascript:void(0)" data-toggle="#hidden2">Toggle Hidden Div</a>
<div class="hidden" id="hidden2" style="display: none;" data-hidden="true">This content is normally hidden</div>
<a href="javascript:void(0)" data-toggle="#hidden3">Toggle Hidden Div</a>
<div class="hidden" id="hidden3" style="display: none;" data-hidden="true">This content is normally hidden</div>
끝 - < 스니핏 >;!
실제로 나는 아니예 포쿠사우스 응답됨 '깜짝' 이벤트:
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
var button = document.getElementById('button');
button.addEventListener('click', function(e){
e.target.style.backgroundColor = 'green';
});
button.addEventListener('focusout', function(e){
e.target.style.backgroundColor = '';
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button id="button">Click</button>
</body>
</html>
끝 - < 스니핏 >;!