bootstrap延迟悬停下拉菜单

时间:2015-12-28 18:01:15

标签: jquery twitter-bootstrap drop-down-menu

我正在尝试使用自举下拉菜单在悬停时打开/关闭,但仅限桌面延迟250毫秒

的javascript:

$(document).ready(function() {
if ($(window).width() > 767) {
    $(".dropdown-toggle").click(function() {
        return false;
    });

    var hoverTimeout;
    $(".dropdown-toggle, .dropdown-menu").hover(function() {
        hoverTimeout = setTimeout(function(){
            $(this).parent(".dropdown").addClass("open");
        }, 250);
    },function() {
        clearTimeout(hoverTimeout);
        setTimeout(function() {
            $(this).parent(".dropdown").removeClass("open");
        }, 250);
    });
}
});

这是HTML结构,但它是文档中建议的正常引导结构:

<!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="happyMenu">
                <ul class="nav navbar-nav navbar-right">
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle"
                           data-toggle="dropdown" role="button"
                           aria-haspopup="true" aria-expanded="false">
                            Title
                        </a>
                        <ul class="container dropdown-menu">
                            <li>
                                <a href="#">
                                    List Title
                                </a>
                                <ul>
                                    <li>
                                        <a href="#">
                                            List Item
                                        </a>
                                    </li>
                                </ul>
                            </li>
                        </ul>                         
                    </li>
                </ul>
            </div><!-- /.navbar-collapse -->

上面的jquery代码不会添加dropdown-toggle的'open'类父级。

1 个答案:

答案 0 :(得分:0)

这是我使用javascript setTimeout函数而不触及HTML结构的解决方案:

javascript:

$(document).ready(function() {
if ($(window).width() > 767) {
    $(".dropdown-toggle").click(function() {
        return false;
    });

    var hoverTimeout;
    $(".dropdown-toggle").hover(function() {
        var element = $(this).parent(".dropdown");
        hoverTimeout = setTimeout(function(){
            element.addClass("open");
        }, 250);
    },function() {
        clearTimeout(hoverTimeout);
        var element = $(this).parent(".dropdown");
        hoverTimeout = setTimeout(function() {
            element.removeClass("open");
        }, 250);

        $(".dropdown-menu").hover(function(){
            clearTimeout(hoverTimeout);  
        },function(){
            setTimeout(function() {
                element.removeClass("open");
            }, 250);
        });
    });
}
});