auto-complete search suggestion drop-down popup

前端 未结 3 1299
南旧
南旧 2021-01-24 08:08

Im trying to make a popup div (when a text-box value changes) and it can be closed (visibility: none) by clicking anywhere outside the div. Similar to Google suggestion drop-dow

相关标签:
3条回答
  • 2021-01-24 08:15

    The jquery solution would be

    $("body > div").click(function() {
    if ($(this).attr("id") == "div-id") {
        // inside the DIV
    } else {
        // not inside the DIV
    }
    });
    

    or

    $("html").click(function (e)
    {
    if (e.target == document.getElementById("div-id"))
        alert("Inside DIV");
    else
        alert("Outside DIV!");
    });
    

    or Javascript snippet would be something like this:

    <script type="text/javascript"> 
    document.onclick=check; 
    function check(e){ 
    var target = (e && e.target) || (event && event.srcElement); 
    var obj = document.getElementById('div-id'); 
    if(target!=obj){obj.style.display='none'} 
    } 
    </script>
    
    0 讨论(0)
  • 2021-01-24 08:30

    One method would be to popup a div behind that covers the whole screen (invisible), and capture clicks on that div to close both popup divs. You could also try capturing clicks on the body tag and that should catch clicks anywhere outside the div (or inside the div as well if events bubble - you may want to perform some testing).

    Sometimes an easier method is to use a timeout, like popup CSS menus that disappear once your mouse has been off of the menu for a couple of seconds. You can catch the onmouseleave event, start a timer, and as long as there isn't another onmouseenter in say, two seconds, then hide the popup div.

    Hope this helps!

    0 讨论(0)
  • 2021-01-24 08:30

    Here's an example with jQuery. If you click on the "test" text, you make the other text appear. Clicking anywhere else except than on the newly appeared text makes it disappear.

    This works because if the click happened inside (the .toggle object, in this case), we call e.stopPropagation() for the click event to stop propagating further up towards the entire window. However if the click occurred somewhere else, it propagates directly to the window and makes .toggle disappear.

    See example of it working on jsfiddle.

    <script src="js/jquery-1.4.4.min.js"></script>
    <script>
        $(function(){
            $('.test').bind('click', function(e){ 
                $('.toggle').fadeIn(); 
                e.stopPropagation();
            });
            $('.toggle').bind('click', function(e){ 
                e.stopPropagation(); 
            });
            $(document).bind('click', function(){ 
                $('.toggle').fadeOut(); 
            });
        });
    </script>
    
    <a class="test" href="#">test</a>
    <div class="toggle">asdasdsa</div>
    
    0 讨论(0)
提交回复
热议问题