• bootstrap中的dropdown组件扩展hover事件


     bootstrap的下拉组件,需要点击click时,方可展示下拉列表。因此对于喜欢简单少操作的大家来说,点击一下多少带来不便,因此,引入hover监听,鼠标经过自动展示下拉框。其实在bootstrap导航条当中dropdown组件用得特别频繁啦!

    如何实现这个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元素代码:

    <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown"></a>

    可以通过数据属性设置选项,也可以通过data-delay和data-close-others来设置选项

    <a href="#" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="1000" data-close-others="false"></a>

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

    .nav> li:hover .dropdown-menu {display: block;}
    

    这样一句代码也能实现想要的hover效果,只不过如果在hover的时候点击组件,再去hover另一个组件就会出现如下效果:

  • 相关阅读:
    php 3des加密解密
    mysql 用命令导入导出
    ubuntu16.04对硬盘进行分区格式化并设置开机自动挂载
    nginx
    iostat (转https://www.cnblogs.com/ftl1012/p/iostat.html)
    zabbix
    zabbix
    mac 录屏
    利用elasticsearch-dump实现es索引数据迁移附脚本
    rdbtool
  • 原文地址:https://www.cnblogs.com/EnderH/p/5371712.html
Copyright © 2020-2023  润新知