auto-complete search suggestion drop-down popup

左心房为你撑大大i 提交于 2019-12-02 07:04:40

问题


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-down.

How can I know weather the mouse click has happened inside the div or outside.

I need to implement this using javascript and jsp.

Please help.


回答1:


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>



回答2:


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!




回答3:


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>


来源:https://stackoverflow.com/questions/5176587/auto-complete-search-suggestion-drop-down-popup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!