사용자가 외부에서 클릭 할 때 jQuery를 사용하여 DIV를 숨기십시오.

StackOverflow https://stackoverflow.com/questions/1403615

  •  05-07-2019
  •  | 
  •  

문제

이 코드를 사용하고 있습니다.

$('body').click(function() {
   $('.form_wrapper').hide();
});

$('.form_wrapper').click(function(event){
   event.stopPropagation();
});

그리고이 HTML :

<div class="form_wrapper">
   <a class="agree" href="javascript:;">I Agree</a>
   <a class="disagree" href="javascript:;">Disagree</a>
</div>

문제는 DIV 내부에 링크가 있고 클릭하면 더 이상 작동하지 않을 때입니다.

도움이 되었습니까?

해결책

같은 문제가 있었고이 쉬운 해결책을 제시했습니다. 재귀적인 일이 있습니다.

$(document).mouseup(function(e) 
{
    var container = $("YOUR CONTAINER SELECTOR");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
        container.hide();
    }
});

다른 팁

당신은 다음과 같은 것을 가지고 더 나은 것입니다 :

var mouse_is_inside = false;

$(document).ready(function()
{
    $('.form_content').hover(function(){ 
        mouse_is_inside=true; 
    }, function(){ 
        mouse_is_inside=false; 
    });

    $("body").mouseup(function(){ 
        if(! mouse_is_inside) $('.form_wrapper').hide();
    });
});

이 코드는 페이지의 클릭 이벤트를 감지 한 다음 #CONTAINER 요소가 클릭 한 경우에만 요소가 #CONTAINER 요소도 후손 중 하나입니다.

$(document).on('click', function (e) {
    if ($(e.target).closest("#CONTAINER").length === 0) {
        $("#CONTAINER").hide();
    }
});

스톱 포거레이션에 의존하는 대신 신체를 발사하는 클릭 이벤트의 대상을 확인할 수 있습니다.

같은 것 :

$("body").click
(
  function(e)
  {
    if(e.target.className !== "form_wrapper")
    {
      $(".form_wrapper").hide();
    }
  }
);

또한 신체 요소에는 브라우저에 표시된 전체 시각적 공간이 포함되지 않을 수 있습니다. 클릭이 등록되지 않는 경우 대신 HTML 요소에 대한 클릭 핸들러를 추가해야 할 수도 있습니다.

라이브 데모

CHECK CLICK 영역이 대상 요소 또는 자식에 있지 않습니다.

$(document).click(function (e) {
    if ($(e.target).parents(".dropdown").length === 0) {
        $(".dropdown").hide();
    }
});

업데이트:

jQuery 정지 전파가 최상의 솔루션입니다

라이브 데모

$(".button").click(function(e){
    $(".dropdown").show();
     e.stopPropagation();
});

$(".dropdown").click(function(e){
    e.stopPropagation();
});

$(document).click(function(){
    $(".dropdown").hide();
});
$(document).click(function(event) {
    if ( !$(event.target).hasClass('form_wrapper')) {
         $(".form_wrapper").hide();
    }
});

솔루션을 업데이트했습니다.

  • 대신 마우스 센터와 마우셀 리브를 사용하십시오
  • 호버 사용 라이브 이벤트 바인딩

var mouseOverActiveElement = false;

$('.active').live('mouseenter', function(){
    mouseOverActiveElement = true; 
}).live('mouseleave', function(){ 
    mouseOverActiveElement = false; 
});
$("html").click(function(){ 
    if (!mouseOverActiveElement) {
        console.log('clicked outside active element');
    }
});

jQuery가없는 솔루션 가장 인기있는 대답:

document.addEventListener('mouseup', function (e) {
    var container = document.getElementById('your container ID');

    if (!container.contains(e.target)) {
        container.style.display = 'none';
    }
}.bind(this));

MDN : https://developer.mozilla.org/en/docs/web/api/node/contains

라이브 데모 ESC 기능

둘 다에서 작동합니다 데스크탑 및 모바일

var notH = 1,
    $pop = $('.form_wrapper').hover(function(){ notH^=1; });

$(document).on('mousedown keydown', function( e ){
  if(notH||e.which==27) $pop.hide();
});

어떤 경우에는 문서를 클릭 할 때 요소가 실제로 보이는지 확인해야합니다. if($pop.is(':visible') && (notH||e.which==27)) $pop.hide();

이런 일이 작동하지 않습니까?

$("body *").not(".form_wrapper").click(function() {

});

또는

$("body *:not(.form_wrapper)").click(function() {

});

슬레이커조차도 :

$("html").click(function(){ 
    $(".wrapper:visible").hide();
});

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();
    }
});

하나의 특정 요소를 숨기려면 DOM을 클릭하는 모든 단일 클릭을 듣는 대신 tabindex 부모에게 <div> 그리고 말을 듣습니다 focusout 이벤트.

환경 tabindex 그것을 확인할 것입니다 blur 이벤트가 시작됩니다 <div> (일반적으로 그렇지 않습니다).

따라서 HTML은 다음과 같습니다.

<div class="form_wrapper" tabindex="0">
    <a class="agree" href="javascript:;">I Agree</a>
    <a class="disagree" href="javascript:;">Disagree</a>
</div>

그리고 당신의 JS :

$('.form_wrapper').on('focusout', function(event){
    $('.form_wrapper').hide();
});

다음은 다른 스레드에서 찾은 JSFiddle입니다. ESC 키와 함께 작동합니다. http://jsfiddle.net/s5ftb/404

    var button = $('#open')[0]
    var el     = $('#test')[0]

    $(button).on('click', function(e) {
      $(el).show()
      e.stopPropagation()
    })

    $(document).on('click', function(e) {
      if ($(e.target).closest(el).length === 0) {
        $(el).hide()
      }
    })

    $(document).on('keydown', function(e) {
      if (e.keyCode === 27) {
        $(el).hide()
      }
    })

PRC322의 멋진 대답을 구축했습니다.

function hideContainerOnMouseClickOut(selector, callback) {
  var args = Array.prototype.slice.call(arguments); // Save/convert arguments to array since we won't be able to access these within .on()
  $(document).on("mouseup.clickOFF touchend.clickOFF", function (e) {
    var 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();
      $(document).off("mouseup.clickOFF touchend.clickOFF");
      if (callback) callback.apply(this, args);
    }
  });
}

이것은 몇 가지를 추가합니다 ...

  1. "무제한"args가있는 콜백이있는 함수 내에 배치
  2. jQuery 's .off ()에 호출을 추가하여 이벤트 네임 스페이스와 짝을 이루어 문서가 실행되면 이벤트를 풀어주었습니다.
  3. 모바일 기능을위한 터치 엔드가 포함되어 있습니다

나는 이것이 누군가를 돕기를 바랍니다!

var n = 0;
$("#container").mouseenter(function() {
n = 0;

}).mouseleave(function() {
n = 1;
});

$("html").click(function(){ 
if (n == 1) {
alert("clickoutside");
}
});

iOS에 문제가있는 경우 Mouseup이 Apple 장치에서 작동하지 않습니다.

jQuery의 Mousedown /Mouseup은 iPad에서 작동합니까?

나는 이것을 사용한다 :

$(document).bind('touchend', function(e) {
        var container = $("YOURCONTAINER");

          if (container.has(e.target).length === 0)
          {
              container.hide();
          }
      });
 $('body').click(function(event) {
    if (!$(event.target).is('p'))
    {
        $("#e2ma-menu").hide();
    }
});

p 요소 이름입니다. ID 또는 클래스 또는 요소 이름도 전달할 수있는 곳입니다.

.form_wrapper를 클릭하면 false를 반환합니다.

$('body').click(function() {
  $('.form_wrapper').click(function(){
  return false
});
   $('.form_wrapper').hide();
});

//$('.form_wrapper').click(function(event){
//   event.stopPropagation();
//});

폼 래퍼 외부의 최상위 요소에 클릭 이벤트를 첨부하십시오.

$('#header, #content, #footer').click(function(){
    $('.form_wrapper').hide();
});

이것은 터치 장치에서도 작동합니다. 선택기 목록에 .form_wrapper의 부모가 포함되지 않도록하십시오.

(PRC322의 답변에 추가하십시오.)

내 경우에는이 코드를 사용하여 사용자가 적절한 탭을 클릭 할 때 나타나는 탐색 메뉴를 숨기고 있습니다. 추가 상태를 추가하는 것이 유용하다는 것을 알았습니다. 컨테이너 외부의 클릭 대상은 ~ 아니다 링크.

$(document).mouseup(function (e)
{
    var container = $("YOUR CONTAINER SELECTOR");

    if (!$("a").is(e.target) // if the target of the click isn't a link ...
        && !container.is(e.target) // ... or the container ...
        && container.has(e.target).length === 0) // ... or a descendant of the container
    {
        container.hide();
    }
});

내 사이트의 일부 링크가 페이지에 새 콘텐츠를 추가하기 때문입니다. 이 새 컨텐츠가 내비게이션 메뉴가 사라지는 동시에 추가되면 사용자를 위해 방향을 전할 수 있습니다.

$(document).ready(function() {
	$('.modal-container').on('click', function(e) {
	  if(e.target == $(this)[0]) {
		$(this).removeClass('active'); // or hide()
	  }
	});
});
.modal-container {
	display: none;
	justify-content: center;
	align-items: center;
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0,0,0,0.5);
	z-index: 999;
}

.modal-container.active {
    display: flex;  
}

.modal {
	width: 50%;
	height: auto;
	margin: 20px;
	padding: 20px;
	background-color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-container active">
	<div class="modal">
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ac varius purus. Ut consectetur viverra nibh nec maximus. Nam luctus ligula quis arcu accumsan euismod. Pellentesque imperdiet volutpat mi et cursus. Sed consectetur sed tellus ut finibus. Suspendisse porttitor laoreet lobortis. Nam ut blandit metus, ut interdum purus.</p>
	</div>
</div>

복사 https://sdtuts.com/click-on-not-pecified-lement/

라이브 데모 http://demos.sdtuts.com/click-on-pecified-element

$(document).ready(function () {
    var is_specified_clicked;
    $(".specified_element").click(function () {
        is_specified_clicked = true;
        setTimeout(function () {
            is_specified_clicked = false;
        }, 200);
    })
    $("*").click(function () {
        if (is_specified_clicked == true) {
//WRITE CODE HERE FOR CLICKED ON OTHER ELEMENTS
            $(".event_result").text("you were clicked on specified element");
        } else {
//WRITE CODE HERE FOR SPECIFIED ELEMENT CLICKED
            $(".event_result").text("you were clicked not on specified element");
        }
    })
})

나는 이것을 좋아했다 :

var close = true;

$(function () {

    $('body').click (function(){

        if(close){
            div.hide();
        }
        close = true;
    })


alleswasdenlayeronclicknichtschliessensoll.click( function () {   
        close = false;
    });

});
dojo.query(document.body).connect('mouseup',function (e)
{
    var obj = dojo.position(dojo.query('div#divselector')[0]);
    if (!((e.clientX > obj.x && e.clientX <(obj.x+obj.w)) && (e.clientY > obj.y && e.clientY <(obj.y+obj.h))) ){
        MyDive.Hide(id);
    }
});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("#hide").click(function(){
    $("p").hide();
  });
  $("#show").click(function(){
    $("p").show();
  });
});
</script>
</head>
<body>
<p>If you click on the "Hide" button, I will disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>

var exclude_div = $("#ExcludedDiv");;  
$(document).click(function(e){
   if( !exclude_div.is( e.target ) )  // if target div is not the one you want to exclude then add the class hidden
        $(".myDiv1").addClass("hidden");  

}); 

깡깡이

이 코드를 사용하면 원하는만큼의 항목을 숨길 수 있습니다.

var boxArray = ["first element's id","second element's id","nth element's id"];
   window.addEventListener('mouseup', function(event){
   for(var i=0; i < boxArray.length; i++){
    var box = document.getElementById(boxArray[i]);
    if(event.target != box && event.target.parentNode != box){
        box.style.display = 'none';
    }
   }
})

너무 많은 답변은 하나를 추가 할 권리가 있어야합니다 ... 나는 현재 (jQuery 3.1.1) 답변을 보지 못했습니다.

$(function() {
    $('body').on('mouseup', function() {
        $('#your-selector').hide();
    });
});

당신이 할 수있는 것은 드롭 다운 외부의 무언가가 클릭되면 드롭 다운을 숨길 수있는 문서에 클릭 이벤트를 바인딩하는 것입니다. 그러나 드롭 다운 내부의 무언가가 클릭되면 숨기지 않으므로 "show"이벤트 (또는 슬라이드 타운 등 드롭 다운 표시)

    $('.form_wrapper').show(function(){

        $(document).bind('click', function (e) {
            var clicked = $(e.target);
            if (!clicked.parents().hasClass("class-of-dropdown-container")) {
                 $('.form_wrapper').hide();
            }
        });

    });

그런 다음 숨길 때 클릭 이벤트를 풀어주십시오

$(document).unbind('click');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top