Подтвердить что ты не робот

Используйте jQuery, чтобы скрыть DIV, когда пользователь нажимает на него

Я использую этот код:

$('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 и когда они больше не работают при нажатии.

4b9b3361

Ответ 1

У той же проблемы возникло это простое решение. Он даже работает рекурсивным:

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

Ответ 2

Вам лучше пойти с чем-то вроде этого:

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

Ответ 3

Этот код обнаруживает любое событие клика на странице, а затем скрывает элемент #CONTAINER тогда и только тогда, когда элемент, нажатый, не был ни элементом #CONTAINER, ни одним из его потомков.

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

Ответ 4

Возможно, вы захотите проверить цель события клика, который срабатывает для тела, вместо того, чтобы полагаться на stopPropagation.

Что-то вроде:

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

Кроме того, элемент body может не включать все видимое пространство, отображаемое в браузере. Если вы заметили, что ваши клики не регистрируются, вам может потребоваться добавить обработчик кликов для HTML-элемента.

Ответ 5

Live DEMO

Проверьте область щелчка не в целевом элементе или в нем дочернем

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

ОБНОВИТЬ:

JQuery остановить распространение является лучшим решением

Live DEMO

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

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

$(document).click(function(){
    $(".dropdown").hide();
});

Ответ 6

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

Ответ 7

Обновлено решение:

  • используйте mouseenter и mouseleave вместо
  • привязки привязки к действию в реальном времени

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

Ответ 9

Демонстрационная версия с функциональностью 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();

Ответ 10

Не было бы такого, как эта работа?

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

});

или

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

});

Ответ 11

Даже омыватель:

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

Ответ 12

Здесь 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()
      }
    })

Ответ 13

А для устройств Touch, таких как 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();
    }
});

Ответ 14

Вместо того, чтобы прослушивать каждый щелчок по 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();
});

Ответ 15

Построен для превосходного ответа 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);
    }
  });
}

Это добавляет пару вещей...

  • Размещается внутри функции с обратным вызовом с "неограниченными" аргументами
  • Добавлен вызов jquery.off() в паре с пространством имен событий, чтобы отменить событие из документа после его запуска.
  • Включено касание для мобильных функций.

Надеюсь, это поможет кому-то!

Ответ 16

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

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

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

Ответ 17

Если у вас проблемы с ios, mouseup не работает на яблочном устройстве.

делает mousedown/mouseup в jquery для ipad?

i использую это:

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

          if (container.has(e.target).length === 0)
          {
              container.hide();
          }
      });

Ответ 18

 $('body').click(function(event) {
    if (!$(event.target).is('p'))
    {
        $("#e2ma-menu").hide();
    }
});

p - это имя элемента. Там, где можно передать идентификатор или имя класса или элемента.

Ответ 19

Возвращает false, если вы нажмете на .form_wrapper:

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

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

Ответ 20

Прикрепите элемент click к элементам верхнего уровня вне оболочки формы, например:

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

Это также будет работать на сенсорных устройствах, просто убедитесь, что вы не включили родительский элемент .form_wrapper в свой список селекторов.

Ответ 21

(Просто добавьте ответ 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();
    }
});

Это связано с тем, что некоторые ссылки на моем сайте добавляют новый контент на страницу. Если этот новый контент добавляется одновременно с исчезновением меню навигации, он может быть дезориентирован для пользователя.

Ответ 22

$(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>

Ответ 23

Скопировано с https://sdtuts.com/click-on-not-specified-element/

Живая демоверсия http://demos.sdtuts.com/click-on-specified-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");
        }
    })
})

Ответ 24

я сделал это так:

var close = true;

$(function () {

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

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


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

});

Ответ 25

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

Ответ 26

<!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>

Ответ 28

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");  

}); 

Ответ 29

Используя этот код, вы можете скрыть столько элементов, сколько хотите

var boxArray = ["first element id","second element id","nth element 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';
    }
   }
})

Ответ 30

Так много ответов, должно быть право прохода, чтобы добавить один... Я не видел текущих (jQuery 3.1.1) ответов - так:

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