在调整大小脚本中取消 Jquery 悬停调用



我有一个基本列表:

<ul class="mainNav">
<li class="menuparent"><a href="#">level one a</a><ul>
    <li><a href="#">level two a</a></li>
    <li><a href="#">level two b</a></li>
    <li><a href="#">level two c</a></li>
</ul></li>
<li><a href="#">level one b</a></li>
</ul>

当页面加载大于600px时,以下Jquery用于通过淡入/淡出显示和隐藏二级导航:

$('li.menuparent').hover(function(){
        $(this).children('ul').fadeIn('slow');
    },function() {
         $(this).children('ul').fadeOut('slow');
});

但是,当浏览器窗口缩放到小于 600px 时,我使用以下 Jquery 通过切换显示/隐藏第二级导航:

$('li.menuparent').click(function(event) {
    $(this).children('ul').toggle();
});

我的问题是,即使我已经将窗口缩小到 600px 以下,因为它加载的比悬停 jquery(淡入/淡出)仍在操作而不是切换的要大。

我是否使用 stop(),如果是这样,我的代码应该是什么,因为我尝试了以下内容,但它不起作用

$('li.menuparent').hover(function() {
    $(this).children('ul').stop();
});

尝试

var $lis = $('li.menuparent'),
    flag;
$(window).resize(function () {
    var width = $(window).width();
    if (flag != 1 && width < 500) {
        flag = 1;
        $lis.on('click.toggle', function (event) {
            $(this).children('ul').toggle();
        }).off('mouseenter.toggle mouseleave.toggle')
    } else if (flag != 2 && width >= 500) {
        flag = 2;
        $lis.on('mouseenter.toggle', function (event) {
            $(this).children('ul').stop(true, true).fadeIn('slow');
        }).on('mouseleave.toggle', function (event) {
            $(this).children('ul').stop(true, true).fadeOut('slow');
        }).off('click.toggle');
    }
}).resize()

演示:小提琴

我会使用事件委托将事件处理与窗口调整大小事件分开,然后通过添加/删除类来控制它。

$(".mainNav").on("click.toggle",".menuparent.clickable",function(){
    $(this).children('ul').toggle();
}).on("mouseenter.toggle",".menuparent.hoverable",function(){
    $(this).children('ul').fadeIn('slow');
}).on("mouseleave.toggle",".menuparent.hoverable",function(){
    $(this).children('ul').fadeOut('slow');
});
$(window).resize(function(){
    var width = $(window).width();
    if (width < 600) {
        $("li.menuparent").removeClass("hoverable").addClass("clickable");
    }
    else {
        $("li.menuparent").addClass("hoverable").removeClass("clickable");
    }
}).resize();

演示:http://jsfiddle.net/RpA9W/

最新更新