1041

私はこのコードを使用しています:

$('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クリックするとリンクが機能しなくなることです。

4

37 に答える 37

2624

同じ問題があったので、この簡単な解決策を思いつきました。それは再帰的にも機能しています:

$(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();
    }
});
于 2011-09-12T09:19:34.130 に答える
211

次のようなものを使用することをお勧めします。

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();
    });
});
于 2009-09-10T06:23:36.110 に答える
101

このコードは、ページ上のクリックイベントを検出し、クリックされた要素が要素でもその子孫でも#CONTAINERない場合にのみ、要素を非表示にします。#CONTAINER

$(document).on('click', function (e) {
    if ($(e.target).closest("#CONTAINER").length === 0) {
        $("#CONTAINER").hide();
    }
});
于 2013-05-09T20:13:27.637 に答える
77

stopPropagationに依存するのではなく、本体に対して発生するクリックイベントのターゲットを確認することをお勧めします。

何かのようなもの:

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

また、body要素には、ブラウザに表示される視覚空間全体が含まれていない場合があります。クリックが登録されていないことに気付いた場合は、代わりにHTML要素のクリックハンドラーを追加する必要があります。

于 2009-09-10T06:20:30.737 に答える
52

ライブデモ

クリック領域がターゲット要素またはその子にないことを確認してください

$(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();
});
于 2014-04-29T08:28:54.963 に答える
21
$(document).click(function(event) {
    if ( !$(event.target).hasClass('form_wrapper')) {
         $(".form_wrapper").hide();
    }
});
于 2009-09-10T06:39:15.557 に答える
19

最も人気のある答えのための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

于 2015-07-27T12:40:17.950 に答える
18

ソリューションを次のように更新しました:

  • 代わりに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');
    }
});
于 2011-04-27T14:32:50.710 に答える
10

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

于 2013-09-15T20:57:31.827 に答える
9

このようなものはうまくいきませんか?

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

});

また

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

});
于 2011-01-26T22:56:35.000 に答える
8

DOMを1回クリックするたびにリッスンして特定の要素を非表示にする代わりに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();
});
于 2015-06-18T18:01:20.623 に答える
7

sleakerでさえ:

$("html").click(function(){ 
    $(".wrapper:visible").hide();
});
于 2011-08-10T20:58:45.370 に答える
7

非常に多くの回答があり、1つ追加するには通過儀礼である必要があります...現在の(jQuery 3.1.1)回答が表示されませんでした-そう:

$(function() {
    $('body').on('mouseup', function() {
        $('#your-selector').hide();
    });
});
于 2018-04-28T11:31:07.850 に答える
6

これが別のスレッドで見つけた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()
      }
    })
于 2013-07-18T01:06:51.387 に答える
6

また、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();
    }
});
于 2014-04-27T07:17:39.967 に答える
6

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

これは、私のサイトの一部のリンクがページに新しいコンテンツを追加するためです。ナビゲーションメニューが消えると同時にこの新しいコンテンツが追加された場合、ユーザーの方向を混乱させる可能性があります。

于 2014-11-11T10:48:24.490 に答える
6

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. 「無制限」の引数を持つコールバックを持つ関数内に配置されます
  2. イベント名前空間と組み合わせたjqueryの.off()の呼び出しを追加して、実行後にドキュメントからイベントのバインドを解除しました。
  3. モバイル機能用のタッチエンドが含まれています

これが誰かに役立つことを願っています!

于 2016-03-24T16:09:31.577 に答える
5

iOSで問題が発生した場合、mouseupはAppleデバイスで機能していません。

jqueryのmousedown/mouseupはiPadで機能しますか?

私はこれを使用します:

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

          if (container.has(e.target).length === 0)
          {
              container.hide();
          }
      });
于 2013-05-14T07:56:00.960 に答える
4
var n = 0;
$("#container").mouseenter(function() {
n = 0;

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

$("html").click(function(){ 
if (n == 1) {
alert("clickoutside");
}
});
于 2011-07-12T16:37:14.603 に答える
4
 $('body').click(function(event) {
    if (!$(event.target).is('p'))
    {
        $("#e2ma-menu").hide();
    }
});

p要素名です。ID、クラス、または要素名も渡すことができます。

于 2013-07-19T07:17:54.970 に答える
4

https://sdtuts.com/click-on-not-specificed-element/からコピー

ライブデモhttp://demos.sdtuts.com/click-on-specificed-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");
        }
    })
})
于 2018-06-14T07:52:27.477 に答える
3

.form_wrapperをクリックするとfalseを返します。

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

//$('.form_wrapper').click(function(event){
//   event.stopPropagation();
//});
于 2014-01-13T10:15:39.083 に答える
3

フォームラッパーの外側の最上位要素にクリックイベントをアタッチします。次に例を示します。

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

これはタッチデバイスでも機能します。セレクターのリストに.form_wrapperの親が含まれていないことを確認してください。

于 2014-02-25T16:01:56.483 に答える
3

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

}); 

フィドル

于 2015-01-29T10:03:56.730 に答える
3

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

于 2016-10-21T12:15:22.430 に答える
2

あなたができることは、クリックイベントをドキュメントにバインドすることです。これは、ドロップダウンの外側の何かがクリックされた場合にドロップダウンを非表示にしますが、ドロップダウンの内側の何かがクリックされた場合は非表示にしないため、「表示」イベント(またはスライドダウンなど)ドロップダウンを表示します)

    $('.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');
于 2011-08-23T22:48:56.260 に答える
2

私はこのようにしました:

var close = true;

$(function () {

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

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


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

});
于 2013-11-19T12:46:26.663 に答える
2
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);
    }
});
于 2013-12-25T00:20:39.083 に答える
2

このコードを使用すると、必要な数のアイテムを非表示にできます

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';
    }
   }
})
于 2015-09-11T15:03:32.827 に答える
1

ドキュメントによると、タグ.blur()以上の機能があります。<input>例えば:

$('.form_wrapper').blur(function(){
   $(this).hide();
});
于 2011-08-12T12:35:48.233 に答える
1

ポップアップウィンドウで承認された回答を使用すると、いくつかの問題が発生する可能性があります。ランダムな場所をクリックすると、望ましくないアクションが発生する場合があります。つまり、ボタンを誤ってクリックすると、新しいページに移動する場合があります。

これが最も効率的な解決策かどうかはわかりませんが、これを防ぐために、スクリーンマスクを使用することをお勧めします。スクリーンマスクがタグのすぐ下にあることを確認して、<body>すべての画面をでカバーできるようにしますwidth:100%; height: 100%。また、何よりも。による要素であることに注意してくださいz-index: 99スクリーンマスクがアクティブなときに別のアイテムまたはdivをクリックできるようにする場合は、そのアイテムまたはdivに高いz-indexを割り当てるだけです。

スクリーンマスクは最初は表示されません(displayed:none)、クリックすると非表示関数を呼び出します(onclick="hidemenu()")。

<body>
<div class="screenmask" onclick="hidemenu()" style="position:fixed; width: 100%; height: 100%; top: 0px; right: 0px; display: none; z-index: 99;"></div>

「同じページ上の複数の異なるポップアップメニュー」を処理するjavascript関数は、次のようになります。

<script>
// an element with onclick="showmenu('id_here')" pops a menu in the screen
function showmenu(id) {  
  var popmenu = document.getElementById(id); // assume popmenu is of class .cardmenu
  $('.cardmenu').hide();   // clear the screen from other popmenus first
  $(popmenu).show();          // pop the desired specific menu
  $('.screenmask').show(); // activate screenmask
}
    
function hidemenu() {      // called when clicked on the screenmask
  $('.cardmenu').hide();   // clear the screen from all the popmenus
  $('.screenmask').hide(); // deactivate screenmask
}
</script>
于 2020-10-29T19:23:52.840 に答える
0
<!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>
于 2014-04-22T12:41:17.033 に答える
0

通常のデバイスとタッチデバイスを切り替えます

しばらく前にここでいくつかの回答を読み、ポップアップバブルとして機能するdivに使用するコードを作成しました。

$('#openPopupBubble').click(function(){
    $('#popupBubble').toggle();

    if($('#popupBubble').css('display') === 'block'){
        $(document).bind('mousedown touchstart', function(e){
            if($('#openPopupBubble').is(e.target) || $('#openPopupBubble').find('*').is(e.target)){
                $(this).unbind(e);
            } 
            else if(!$('#popupBubble').find('*').is(e.target)){
                $('#popupBubble').hide();
                $(this).unbind(e);
            }
        });
    }
});

クラスを使用してこれをより抽象化し、クリックイベントをトリガーしたボタンに基づいて正しいポップアップバブルを選択することもできます。

$('body').on('click', '.openPopupBubble', function(){
    $(this).next('.popupBubble').toggle();

    if($(this).next('.popupBubble').css('display') === 'block'){
        $(document).bind('mousedown touchstart', function(e){
            if($(this).is(e.target) || $(this).find('*').is(e.target)){
                $(this).unbind(e);
            } 
            else if(!$(this).next('.popupBubble').find('*').is(e.target)){
                $(this).next('.popupBubble').hide();
                $(this).unbind(e);
            }
        });
    }
});
于 2015-07-25T18:23:04.663 に答える
0

このソリューションは正常に機能するはずです、それは簡単です:

jQuery(document).ready(function($) {
    jQuery(document).click(function(event) {
        if(typeof  jQuery(event.target).attr("class") != "undefined") {
            var classnottobeclickforclose = ['donotcountmeforclickclass1', 'donotcountmeforclickclass2','donotcountmeforclickclass3'];
            var arresult = jQuery.inArray(jQuery(event.target).attr("class"), classnottobeclickforclose);
            if (arresult < 0) {
                jQuery(".popup").hide();
            }
        }
    });
});

上記のコードでは、ポップアップを表示するために使用したクラスまたはクリックポップアップでdonotcountmeforclickclass1、donotcountmeforclickclass2などを変更しても効果がないため、ポップアップを開くために使用しているクラスを確実に追加する必要があります。

.popupクラスをポップアップクラスに変更します。

于 2019-05-31T11:41:47.843 に答える
0

処理されたキーワードに従ってオートコンプリートを表示する検索ボックスで作業していました。オプションをクリックしたくない場合は、以下のコードを使用して処理済みリストを非表示にします。これで機能します。

$(document).click(function() {
 $('#suggestion-box').html("");
});

提案ボックスは、値を表示しているオートコンプリートコンテナです。

于 2019-07-06T10:42:54.610 に答える
-2
$(document).ready(function() {

$('.headings').click(function () {$('#sub1').css("display",""); });
$('.headings').click(function () {return false;});
$('#sub1').click(function () {return false;});
$('body').click(function () {$('#sub1').css("display","none");

})});
于 2011-11-09T19:05:59.940 に答える
-3

私はそれがはるかに簡単になることができると思います。私はこのようにしました:

$(':not(.form_wrapper)').click(function() {
    $('.form_wrapper').hide();
});
于 2012-09-13T14:10:07.970 に答える