JS组件Bootstrap dropdown组件扩展hover事件

时间:2016-04-2078举报小编:jong

    bootstrap导航条当中dropdown组件用得特别频繁,本文就为大家介绍bootstrap中的dropdown组件扩展hover事件,具体内容如下

    JS组件Bootstrap dropdown组件扩展hover事件

    如何实现这个hover事件呢,其实在dropdown组件的点击事件的基础上很好完成的。细心者可以发现,下拉框出现时,其父级会有一个open的class属性。我们只需要监听hover事件时,给父级增加或删除open类就可以了。

    boostrap-hover-dropdown.js插件,托管在github上的代码网址:

    下面是完整的js插件代码:

    // bootstrap响应式导航条
    ;(function($, window, undefined) {
      // outside the scope of the jQuery plugin to
      // keep track of all dropdowns
      var $allDropdowns = $();
     
      // if instantlyCloseOthers is true, then it will instantly
      // shut other nav items when a new one is hovered over
      $.fn.dropdownHover = function(options) {
     
        // the element we really care about
        // is the dropdown-toggle's parent
        $allDropdowns = $allDropdowns.add(this.parent());
     
        return this.each(function() {
          var $this = $(this).parent(),
            defaults = {
              delay: 500,
              instantlyCloseOthers: true
            },
            data = {
              delay: $(this).data('delay'),
              instantlyCloseOthers: $(this).data('close-others')
            },
            options = $.extend(true, {}, defaults, options, data),
            timeout;
     
          $this.hover(function() {
            if(options.instantlyCloseOthers === true)
              $allDropdowns.removeClass('open');
     
            window.clearTimeout(timeout);
            $(this).addClass('open');
          }, function() {
            timeout = window.setTimeout(function() {
              $this.removeClass('open');
            }, options.delay);
          });
        });
      };
     
      $('[data-hover="dropdown"]').dropdownHover();
    })(jQuery, this);

    可以看到作者在插件前面加了个分号;,增加了插件的兼容性,因为可能上一个js代码没写;,如果在此不加分号则可能因为没换行导致js出错。

    可选参数
    delay: (可选参数) 在毫秒的延迟。这是等待的时间之前关闭下拉当鼠标不再在下拉菜单或按钮/导航项目,激活它。默认值 500。
    instantlyCloseOthers: (可选参数) 一个布尔值,如果为真,将立即关闭所有其他下拉菜单的使用当您启动一个新的选择器匹配导航。默认值 true。

    加上以上js代码后,此时效果还实现不了,因为我们还需要再做一步,就是给元素加上data-*属性:

    data-hover="dropdown"
    完整的HTML元素代码:
    代码如下:
    可以通过数据属性设置选项,也可以通过data-delay和data-close-others来设置选项

    代码如下
    当然,还有最简单的方法,那就是用css的hover控制

    [/code].nav> li:hover .dropdown-menu {display: block;}[/code]
    这样一句代码也能实现想要的hover效果,只不过如果在hover的时候点击组件,再去hover另一个组件就会出现如下效果:

    JS组件Bootstrap dropdown组件扩展hover事件

    以上就是为大家分享的Bootstrap dropdown组件扩展hover事件使用方法,希望对大家熟练掌握hover事件有所帮助。