简体   繁体   English

单击即可消失下拉框

[英]Dropdown Box disappear on click away

This is my first post on here and I'm just learning Jquery so please be kind! 这是我在这里的第一篇文章,我正在学习Jquery,所以请客气! :) :)

I have just created a website - www.wayfairertravel.com and I have some dropdown boxes on my homepage, where users can search 'By Style' etc... 我刚刚创建了一个网站-www.wayfairertravel.com,我的主页上有一些下拉框,用户可以在其中搜索“按样式”等...

At the moment once those boxes are opened you have to close them manually... I'm just wondering if there is a way to change the code there currently so that when a user clicks elsewhere on the page it disappears. 现在,一旦打开了这些框,您就必须手动将其关闭...我只是想知道是否存在一种方法来更改当前的代码,以便当用户单击页面上的其他位置时,它消失了。

Any help greatly appreciated. 任何帮助,不胜感激。 If you you could be as precises in your answer that would be great - Ie where to change the code and what to change to. 如果您可以尽可能精确地回答问题,那就好-即在哪里更改代码以及更改内容。

Cheers, 干杯,

Harry 掠夺

Usually, you add events on body and on the desired dropdown: 通常,您可以在body和所需的下拉列表上添加事件:

$(document.body).on('click', function() {
    dropdown.close(); // .hide(); whatever
});
dropdown.on('click', function(event) {
    event.stopPropagation(); // prevents dropdown from getting closed when clicking on it
});

However, I think there are jQuery plugins for clickOutisde events that you could use too (they probably work like mentioned above, but you don't have to write it yourself). 但是,我认为您也可以使用clickOutisde事件的jQuery插件(它们的工作方式可能如上所述,但您不必自己编写)。

I took Jakub Michálek advice and applied it your code. 我接受了JakubMichálek的建议并将其应用于您的代码。 I prepared fiddle so you can test it out: http://jsfiddle.net/tmuuS/ 我准备了小提琴,因此您可以对其进行测试: http : //jsfiddle.net/tmuuS/

This is your javascript you want to have on your page: 这是您想在页面上使用的JavaScript:

$(document).ready(function () {
    $("#expslider").hide();
    $("#expshower").show();
    $('#expshower').click(function () {
        $("#expslider").slideToggle();
    });

    $(document.body).on('click', function () {
        $("#expslider").slideUp();
    });
    $("#expslider").on('click', function (event) {
        event.stopPropagation(); // prevents dropdown from getting closed when clicking on it
    });
    $("#expshower").on('click', function (event) {
        event.stopPropagation(); // prevents dropdown from getting closed when clicking on it
    });
});

Although remember that it's better to have javascript in head tag, not right beside the place where you use it. 虽然请记住,最好在head标签中使用javascript,而不是在使用它的地方旁边。 (hard to look for it later when you need changes) (以后需要更改时很难找到它)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM