jQuery Ukryj element po kliknięciu w dowolnym miejscu na stronie

Chciałbym wiedzieć, czy jest to prawidłowy sposób ukrywania widocznych elementów Po kliknięciu w dowolnym miejscu na stronie.

$(document).click(function (event) {            
    $('#myDIV:visible').hide();
});

Element (div, span itp.) nie powinien znikać, gdy zdarzenie click wystąpi w granicach elementu.

Author: Ayan, 2009-04-03

17 answers

Jeśli rozumiem, że chcesz ukryć div po kliknięciu w dowolnym miejscu poza div, a jeśli klikniesz, gdy nad div, to nie powinien się zamykać. możesz to zrobić:

$(document).click(function() {
    alert("me");
});
$(".myDiv").click(function(e) {
    e.stopPropagation(); // This is the preferred method.
    return false;        // This should not be used unless you do not want
                         // any click events registering inside the div
});

To wiąże kliknięcie z całą stroną, ale jeśli klikniesz na div, o którym mowa, anuluje Zdarzenie kliknięcia.

 189
Author: Jeremy B.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-27 14:09:37

Spróbuj tego

 $('.myDiv').click(function(e) { //button click class name is myDiv
  e.stopPropagation();
 })

 $(function(){
  $(document).click(function(){  
  $('.myDiv').hide(); //hide the button

  });
});

Używam Nazwa klasy zamiast ID, ponieważ w asp.net musisz się martwić o dodatkowe rzeczy. NET dołącza do id

EDIT - Skoro dodałeś kolejny kawałek, to działałoby to tak:

 $('.myDiv').click(function() { //button click class name is myDiv
  e.stopPropagation();
 })

 $(function(){
  $('.openDiv').click(function() {
  $('.myDiv').show(); 

  });
  $(document).click(function(){  
  $('.myDiv').hide(); //hide the button

  });
});
 21
Author: TStamper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-04-03 16:18:33

Od jQuery 1.7 istnieje nowy sposób obsługi zdarzeń. Pomyślałem, że odpowiem tutaj, aby zademonstrować, jak Mogę to zrobić w "nowy" sposób. Jeśli nie, polecam przeczytać jQuery docs dla metody " on " .

var handler = function(event){
  // if the target is a descendent of container do nothing
  if($(event.target).is(".container, .container *")) return;

  // remove event handler from document
  $(document).off("click", handler);

  // dostuff
}

$(document).on("click", handler);

Tutaj nadużywamy selektorów jQuery i bulgotania zdarzeń. Pamiętaj, że upewniam się, że wyczyszczę później obsługę zdarzenia. Można zautomatyzować to zachowanie za pomocą $('.container').one (patrz: docs ), ale ponieważ musimy zrobić uwarunkowania w / align = "left" /

 18
Author: Ben Taylor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-30 01:27:46

Poniższy przykład kodu wydaje mi się najlepszy. Podczas gdy możesz użyć 'return false', który zatrzymuje całą obsługę tego zdarzenia dla div lub jego dzieci. Jeśli chcesz mieć kontrolki na pop-up div (pop-up formularz logowania na przykład) musisz użyć zdarzenia.stopropogacja ().

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <a id="link" href="#">show box</a>
    <div id="box" style="background: #eee; display: none">
        <p>a paragraph of text</p>
        <input type="file"  />
    </div>

    <script src="jquery.js" type="text/javascript"></script>

    <script type="text/javascript">
        var box = $('#box');
        var link = $('#link');

        link.click(function() {
            box.show(); return false;
        });

        $(document).click(function() {
            box.hide();
        });

        box.click(function(e) {
            e.stopPropagation();
        });

    </script>
</body>
</html>
 13
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-17 16:02:43

Dzięki, Thomas. Jestem nowy w JS i szukałem rozwiązania mojego problemu. Twój pomógł.

Użyłem jquery, aby utworzyć okno logowania, które ślizga się w dół. Aby uzyskać najlepsze wrażenia użytkownika, chciałem, aby pudełko zniknęło, gdy użytkownik kliknie gdzieś, ale pudełko. Jestem trochę zażenowany, że poświęciłem 4 godziny na naprawę tego. Ale jestem nowy w JS.

Może mój kod może komuś pomóc:

<body>
<button class="login">Logg inn</button>
<script type="text/javascript">

    $("button.login").click(function () {
        if ($("div#box:first").is(":hidden")) {
                $("div#box").slideDown("slow");} 
            else {
                $("div#box").slideUp("slow");
                }
    });
    </script>
<div id="box">Lots of login content</div>

<script type="text/javascript">
    var box = $('#box');
    var login = $('.login');

    login.click(function() {
        box.show(); return false;
    });

    $(document).click(function() {
        box.hide();
    });

    box.click(function(e) {
        e.stopPropagation();
    });

</script>

</body>
 6
Author: Tommy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-04-21 11:09:16

Możesz także:

$(document).click(function (e)
{

  var container = $("div");

   if (!container.is(e.target) && container.has(e.target).length === 0)
  {
 container.fadeOut('slow');

   }

});

Jeśli twój cel nie jest div, Ukryj div, sprawdzając jego długość jest równa zeru.

 5
Author: Sandeep Pal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-05 09:34:54

Zrobiłem poniżej. Myślałem o dzieleniu się, aby ktoś inny mógł również skorzystać.

$("div#newButtonDiv").click(function(){
    $(this).find("ul.sub-menu").css({"display":"block"});

    $(this).click(function(event){
        event.stopPropagation();
        $("html").click(function(){
            $(this).find("ul.sub-menu").css({"display":"none"});
        }
    });
});
Daj mi znać, jeśli mogę komuś w tym pomóc.
 5
Author: foxybagga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-19 15:27:58

Inny sposób ukrywania kontenera div, gdy nastąpi kliknięcie w elemencie not children;

$(document).on('click', function(e) {
    if(!$.contains($('.yourContainer').get(0), e.target)) {
        $('.yourContainer').hide();
    }
});
 3
Author: Renato Gama,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-17 18:46:29
  $(document).on('click', function(e) { // Hides the div by clicking any where in the screen
        if ( $(e.target).closest('#suggest_input').length ) {
            $(".suggest_div").show();
        }else if ( ! $(e.target).closest('.suggest_container').length ) {
            $('.suggest_div').hide();
        }
    });

Tutaj # suggest_input in jest nazwą textbox and .suggest_container jest nazwą klasy ul i .suggest_div jest głównym elementem div dla mojego auto-suggest.

Ten kod służy do ukrywania elementów div poprzez kliknięcie dowolnego miejsca na ekranie. Przed zrobieniem każdej rzeczy proszę zrozumieć kod i skopiować go...

 3
Author: Shaikh Arbaaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-28 05:53:37

Spróbuj tego, działa idealnie dla mnie.

$(document).mouseup(function (e)
{
    var searchcontainer = $("#search_container");

    if (!searchcontainer.is(e.target) // if the target of the click isn't the container...
        && searchcontainer.has(e.target).length === 0) // ... nor a descendant of the container
    {
        searchcontainer.hide();
    }
});
 2
Author: Hassan Sardar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-22 06:44:51
$('html').click(function() {
//Hide the menus if it is visible
});

$('#menu_container').click(function(event){
    event.stopPropagation();
});
Ale musisz pamiętać również o tych rzeczach. http://css-tricks.com/dangers-stopping-event-propagation/
 2
Author: Muhammad Tahir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-03 10:49:08

Oto działające rozwiązanie CSS / small JS oparte na odpowiedzi Sandeep Pal:

$(document).click(function (e)
{
  if (!$("#noticeMenu").is(e.target) && $("#noticeMenu").has(e.target).length == 0)
  {
   $("#menu-toggle3").prop('checked', false);
  }
});

Wypróbuj, klikając pole wyboru, a następnie poza menu:

Https://jsfiddle.net/qo90txr8/

 2
Author: Bjoerg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-28 10:08:22

Spróbuj tego:

$(document).mouseup(function (e) {
var div = $("your div");
if (!div.is(e.target) && div.has(e.target).length === 0) 
{
   div.hide();
 }
});
 2
Author: Nalan Madheswaran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-16 06:14:18

To nie działa - ukrywa .myDIV po kliknięciu wewnątrz niego.

$('.openDiv').click(function(e) {
$('.myDiv').show(); 
e.stopPropagation();
})

$(document).click(function(){  
$('.myDiv').hide(); 

});

});

<a class="openDiv">DISPLAY DIV</a>

<div class="myDiv">HIDE DIV</div>
 1
Author: Franek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-04-03 15:58:55

Tylko 2 małe ulepszenia do powyższych sugestii:

  • odłącz dokument.kliknij po zakończeniu
  • Zatrzymaj propagację na zdarzeniu, które to wywołało, zakładając, że jest to kliknięcie

    jQuery(thelink).click(function(e){
        jQuery(thepop).show();
    
        // bind the hide controls
        var jpop=jQuery(thepop);
        jQuery(document).bind("click.hidethepop", function() {
                jpop.hide();
                // unbind the hide controls
                jQuery(document).unbind("click.hidethepop");
        });
        // dont close thepop when you click on thepop
        jQuery(thepop).click(function(e) {
            e.stopPropagation();
        });
        // and dont close thepop now 
        e.stopPropagation();
    });
    
 1
Author: commonpike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-13 16:21:54

$(document).ready(function(){

$("button").click(function(){
   
       
        $(".div3").toggle(1000);
    });
   $("body").click(function(event) {
   if($(event.target).attr('class') != '1' && $(event.target).attr('class') != 'div3'){
       $(".div3").hide(1000);}
    }); 
   
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<button class="1">Click to fade in boxes</button><br><br>

<body style="width:100%;height:200px;background-color:pink;">
<div class="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div><body>
 1
Author: Ehsan KHAN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-16 07:51:51
$(document).mouseup(function (e)
{
    var mydiv = $('div#mydiv');
    if (!mydiv.is(e.target) && mydiv.has(e.target).length === 0){
       search.slideUp();
    }
});
 0
Author: mohammad gitipasand,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-13 15:35:56