bootstrap中的dropdown组件改造click为hover

boostrap的下拉菜单的样式

dropdown样式

如果某个列表项应用dropdown样式,则说明该列表项将会有下拉菜单


dropdown-menu样式

 下拉列表应用dropdown-menu样式,表示该列表作为下拉菜单。


dropdown-toggle样式

应用dropdown样式的列表项的子元素应用dropdown-toggle样式,表示点击该元素就会展开下拉菜单


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

在官网上

bootstrap-hover-dropdown | Bootstrap中文网开源项目免费 CDN 服务
http://www.bootcdn.cn/bootstrap-hover-dropdown/

点击“源码”进入下载地址
https://github.com/CWSpear/bootstrap-hover-dropdown


下面是完整的js插件代码:
// bootstrap响应式导航条
/* @preserve
* Project: Bootstrap Hover Dropdown
* Author: Cameron Spear
* Version: v2.0.11
* Contributors: Mattia Larentis
* Dependencies: Bootstrap's Dropdown plugin, jQuery
* Description: A simple plugin to enable Bootstrap dropdowns to active on hover and provide a nice user experience.
* License: MIT
* Homepage: http://cameronspear.com/blog/bootstrap-dropdown-on-hover-plugin/
*/
;(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) {
    // don't do anything if touch is supported
    // (plugin causes some issues on mobile)
    if('ontouchstart' in document) return this; // don't want to affect chaining

    // 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 = $this.parent(),
            defaults = {
                delay: 500,
                instantlyCloseOthers: true
            },
            data = {
                delay: $(this).data('delay'),
                instantlyCloseOthers: $(this).data('close-others')
            },
            showEvent   = 'show.bs.dropdown',
            hideEvent   = 'hide.bs.dropdown',
            // shownEvent  = 'shown.bs.dropdown',
            // hiddenEvent = 'hidden.bs.dropdown',
            settings = $.extend(true, {}, defaults, options, data),
            timeout;

        $parent.hover(function (event) {
            // so a neighbor can't open the dropdown
            if(!$parent.hasClass('open') && !$this.is(event.target)) {
                // stop this event, stop executing any code
                // in this callback but continue to propagate
                return true;
            }

            openDropdown(event);
        }, function () {
            timeout = window.setTimeout(function () {
                $parent.removeClass('open');
                $this.trigger(hideEvent);
            }, settings.delay);
        });

        // this helps with button groups!
        $this.hover(function (event) {
            // this helps prevent a double event from firing.
            // see https://github.com/CWSpear/bootstrap-hover-dropdown/issues/55
            if(!$parent.hasClass('open') && !$parent.is(event.target)) {
                // stop this event, stop executing any code
                // in this callback but continue to propagate
                return true;
            }

            openDropdown(event);
        });

        // handle submenus
        $parent.find('.dropdown-submenu').each(function (){
            var $this = $(this);
            var subTimeout;
            $this.hover(function () {
                window.clearTimeout(subTimeout);
                $this.children('.dropdown-menu').show();
                // always close submenu siblings instantly
                $this.siblings().children('.dropdown-menu').hide();
            }, function () {
                var $submenu = $this.children('.dropdown-menu');
                subTimeout = window.setTimeout(function () {
                    $submenu.hide();
                }, settings.delay);
            });
        });

        function openDropdown(event) {
            $allDropdowns.find(':focus').blur();

            if(settings.instantlyCloseOthers === true)
                $allDropdowns.removeClass('open');

            window.clearTimeout(timeout);
            $parent.addClass('open');
            $this.trigger(showEvent);
        }
    });
};

$(document).ready(function () {
    // apply dropdownHover to all elements with the data-hover="dropdown" attribute
    $('[data-hover="dropdown"]').dropdownHover();
});
})(jQuery, this);


然后在网页的最后加
<script>
$(function(){
$('.dropdown-toggle').dropdownHover();
$('a.dropdown-toggle').one('click',function(){ location.href= $(this).attr('href'); });
});

</script>



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

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


方案二:

还有一种也很简便的方法

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: 300,
                    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);
            });
        });
    };

   $(document).ready(function () {
    // apply dropdownHover to all elements with the data-hover="dropdown" attribute
    $('[data-hover="dropdown"]').dropdownHover();
})
})(jQuery, this);

加上以上js代码后,需要给元素加上属性  

data-hover="dropdown"

完整的html元素代码:

<a href="#" class="dropdown-toggle head-usr-img" data-toggle="dropdown" data-hover="dropdown">

ps:一些网站在

 $(document).ready(function () {
    // apply dropdownHover to all elements with the data-hover="dropdown" attribute
    $('[data-hover="dropdown"]').dropdownHover();
})
漏写成

  $('[data-hover="dropdown"]').dropdownHover();
这是要注意的,我已经参照方案一的正确经验改过来了


再说一下相关代码的解读:

hover()的语法

$(selector).hover(inFunction,outFunction)

参数 描述
inFunction 必需。规定 mouseover 事件发生时运行的函数。
outFunction 可选。规定 mouseout 事件发生时运行的函数。
 $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);

当鼠标滑过dropdown组件时,添加class属性open,当鼠标离开dropdown组件时,删除class属性open。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值