屏幕尺寸<时,切换下拉列表1200

时间:2016-03-15 09:43:16

标签: javascript jquery html

我在屏幕上写了这样的功能,宽度为> 1200有悬停效果和显示菜单

$(window).resize(function(){
    var width = $(window).innerWidth();
    dropDown(width);
});

var dropDown = function(width){
    if(width > 1200){
        $(".dropdown").hover(function() {
                $('.dropdown-menu', this).stop( true, true ).fadeIn("fast");
                $(this).toggleClass('open');
                $('b', this).toggleClass("caret caret-up");
            }, function() {
                $('.dropdown-menu', this).stop( true, true ).fadeOut("fast");
                $(this).toggleClass('open');
                $('b', this).toggleClass("caret caret-up");
            }
        );
    }
};

问题是当我刷新移动尺寸的页面时 - 一切看起来很好,但随后改变了窗口的大小> 1200px然后改变窗口的大小<当我悬停时,1200px我的dropDown显示,但我不需要它,它必须在我点击时打开。问题出在哪儿?我应该怎么做?

我的HTML

<li class="dropdown">
    <a href="" class="dropdown-toggle" data-toggle="dropdown">DROPDOWN <b class="caret"></b></a>
      <ul class="dropdown-menu">
         <li><a href="#">1</a></li>
         <li><a href="#">2</a></li>
      </ul>
</li>

1 个答案:

答案 0 :(得分:5)

当窗口小于1200宽时,您没有删除悬停处理程序,因此事件处理程序仍然存在且有效。以下else声明的if部分将为您解决这个问题......

var openDropDown = function(el) {
    var $el = $(el);
    $('.dropdown-menu', $el).stop( true, true ).fadeIn("fast");
    $el.toggleClass('open');
    $('b', $el).toggleClass("caret caret-up");
};
var closeDropDown = function(el) {
    var $el = $(el);
    $('.dropdown-menu', $el).stop( true, true ).fadeOut("fast");
    $el.toggleClass('open');
    $('b', $el).toggleClass("caret caret-up");
};

var dropDown = function(width){
    if(width > 1200){
        $(".dropdown")
            .off("click")
            .hover(function() {
                openDropDown(this);
            }, function() {
                closeDropDown(this);
            });
    }
    else {
        $(".dropdown")
            .off("mouseenter mouseleave")
            .on("click", function() {
                if ($(this).hasClass("open")) {
                    closeDropDown(this);
                }
                else {
                    openDropDown(this);
                }
            });
    }
};

我还移动了代码以打开和关闭下拉列表到单独的函数中,以便可以重复使用它。然后我添加了一个单击处理程序,以便在窗口为&lt;时单击时使下拉列表工作。 1200宽。

相关问题