Jquery - Click outside and Hide Div

2019-09-08 15:11发布

I am using this: http://www.useful-dates.com/search/

How should the script be written to say, 1. When the user clicks the input, the scrolled div is shown. 2. When the user click outside of the scrolled div, the scrolled div hides.

Like this, but i have had no luck re-writting the script: http://rob-bell.net/static/ddlist.html

Iv searched and tried all kinds of things on the net and no luck, please help?

2条回答
Emotional °昔
2楼-- · 2019-09-08 15:48

The easiest way of doing this is when your script is triggered to display the list (the scrolled div) it creates a trigger to the click event on the document itself aswell. Something like this:

$("selector to your div").click(function() {
    var scrolledDiv = $("selector to your scrolled div");
    scrolledDiv.show();
    $(document).one(function() {
        scrolledDiv.hide();
    });
});

By using the one() the code to hide the scroll list will only be executed once, so it wont run each time the user is clicking the document. But remember that it will also trigger on clicks inside your scrolling div, if you dont want that stop the propagation of the click event like this:

$("selector to your scrolled div").click(function(e) {
    e.stopPropagation();
});
查看更多
对你真心纯属浪费
3楼-- · 2019-09-08 15:49

If you look at the source code of your example ;

            $(document).click(function(){

                $('.ddcontainer > div > ol').hide();

            });

This hides the div when there has been a click on the document.

Give you div an ID like so:

<div id="searchResults" style="height:95px;width:290px;overflow:scroll;overflow-x:hidden;margin: 2px 0 0 0;">

and then:

$(document).click(function(){

    $('#searchResults').hide();

});

Alternatively and maybe a better solution is to use focus and blur:

$("#kwd_search").focus(function(){
    $('#searchResults').show();
}).blur(function(){
    $('#searchResults').hide();
});

This will show the results when the focus is put onto the input, and removes it when you 'leave' the input.

UPDATE

With the autocomplete plugin, you can perform a task after the item has been selected like this:

$( "#tags" ).autocomplete({
    source: availableTags
}).bind( "autocompleteselect", function(event, ui) {
    location.href = ui.item.value; // If the value of the item is a url, this will forward you to it
});
查看更多
登录 后发表回答