javascript - if 语句中的 jQuery 悬停函数

标签 javascript jquery html css twitter-bootstrap

所以我的 jQuery 代码有问题,当下拉切换具有 data-toggle = 'hover' 时应该在悬停时显示子菜单,如果此切换具有 data-toggle = 'dropdown' 应该只显示子菜单单击时的菜单。 代码似乎可以工作,但是当调整窗口大小并且属性从 HOVER 更改为 DROPDOWN(另一种方式似乎工作得很好)时,悬停功能仍然会执行。

这是代码

function main() {
    if (($('a.dropdown-toggle').attr('data-toggle'))=='hover') {
        $('.dropdown').hover(function() {
            $('ul.dropdown-menu', this).stop(true, true).slideDown(100);
            $(this).addClass('open');
          }, function() {
            $('ul.dropdown-menu', this).stop(true, true).slideUp(100);
            $(this).removeClass('open');
          });
       }
      }
      $(document).ready(main);
      $(window).resize(main);

和属性变化函数

function clickEvent() {
    if(viewport().width <= 991) {
        $('a.dropdown-toggle').attr('data-toggle','dropdown');
    } else {
        $('a.dropdown-toggle').attr('data-toggle','hover');
    }
}
$(document).ready(clickEvent);
$(window).resize(clickEvent);

最佳答案

尝试在事件处理程序中编写一个阻塞条件,

function main() {
    $('.dropdown').hover(function() {
        if ($('a.dropdown-toggle').data('toggle')!=='hover') { return; }
        $('ul.dropdown-menu', this).stop(true, true).slideDown(100);
        $(this).addClass('open');
      }, function() {
        if ($('a.dropdown-toggle').data('toggle')!=='hover') { return; }
        $('ul.dropdown-menu', this).stop(true, true).slideUp(100);
        $(this).removeClass('open');
    });
}

或者更好地在事件绑定(bind)中做一些调整,

//remove the if statement inside of main function and do the below.

function clickEvent() {
    if(viewport().width <= 991) {
        $('.dropdown').unbind('mouseenter mouseleave')
    } else {
        main();
    }
}

关于javascript - if 语句中的 jQuery 悬停函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33283611/

相关文章:

javascript - 在 ReactJS 上使用 Lodash 对映射列表进行排序

javascript - 重置 setTimeout

javascript - 当页面完全加载时从数组中获取单词

javascript - 使用 getElementById(field_name).value 检测字段的设置值并拦截/覆盖它

javascript - 是否有针对 htmlstring 的 JS diff 库,就像纯文本上的 google-diff-match-patch 一样?

javascript - jQuery-UI 禁用某些元素的拖动

javascript - 从 Controller 传递的变量的默认值, Angular 文本框中的 ng-init 未显示

javascript - jQuery 这个父 prev 选择器不工作

javascript - Bootstrap 工具提示 (3.3.6) 显示灰色框

php - html选择不工作