下拉菜单,如果打开它,删除它

时间:2014-09-13 14:13:17

标签: javascript jquery css3

我试图创建下拉菜单,我是这样做的,默认情况下我在下拉菜单上做

.dropdown {
    display: none;
}

然后我在点击时创建事件并基于该上下文切换类

.active { display block; }

现在我无法弄清楚当我点击其他按钮或文档时如何删除.active课程,如果用户点击其他按钮{} 3,我就不想保持下拉活动课程}}

4 个答案:

答案 0 :(得分:0)

评论后更新

您不需要将""this关键字放在一起。您的代码行应为:

$(this).siblings("ul.dropdown").toggleClass("active");

完整代码

$(function () {
var dropdown = $(".btn").find("a");
dropdown.on("click", function() {
$("ul.dropdown.active").removeClass("active");  //added new line
$(this).siblings("ul.dropdown").toggleClass("active");
});
}());

<强> Updated Code with Remove Class

答案 1 :(得分:0)

http://jsfiddle.net/pnLkpxkb/8/

$(function () {
    // The user clicks anywhere in the document
    $(document).click(function (e) {
        // If a dropdown has a class active AND if the dropdown or the link is not the target of the click
        if ($("ul.dropdown").hasClass("active") && !$("ul.dropdown, .btn > a").is(e.target)) {
            // Remove class active
            $("ul.dropdown.active").removeClass("active");
        }
    });
    var dropdown = $(".btn > a");
    // The user clicks on a toggle link (One or Two)
    dropdown.on("click", function () {
        // Remove the active class from the active element
        $("ul.dropdown.active").removeClass("active");
        // Add class to the relevant sub menu
        $(this).siblings("ul.dropdown").addClass("active");
    });
}());

答案 2 :(得分:0)

toggleClass无法正常工作。对于你的情况,我建议采用这种方式:

$(function () {
    var dropdown = $(".btn").find("a");
    dropdown.on("click", function() {
        $("ul.dropdown").removeClass("active");//add this to remove class from all ul .dropdowns
        $(this).siblings("ul.dropdown").addClass("active");//Add class to your ul dropdown. Here you can use toggleClass too
    });

}());

fiddle

答案 3 :(得分:0)

$(function () {
    $(document).on('click', function () {
        $("ul.dropdown").removeClass('active');
    });

    $(".btn a").on("click", function (e) {
        e.stopPropagation();
        $("ul.dropdown").removeClass('active');
        $(this).siblings("ul.dropdown").addClass("active");
    });
});

JSFiddle Demo