在使用bootstrap制作后臺時用到了響應式導航條,其中dropdown組件更是用的比較多,用的多需要點擊的就多,dropdown默認鼠標左鍵單擊才展開,如果使用鼠標放上去(hover)就展開則會省去點擊時間,這樣能提高效率。

原本的改造思路是:給dropdown元素綁定hover事件,hover上去的時候,執行該元素的click事件――即把hover同步為click,hover即為click。
但想到與其自己來改造,不如先在網上搜索搜索看看有沒有現成的插件,果不其然就搜索到了,托管在github上的代碼網址:查看
在這兒就直接把代碼復制出來:
;(function($, window, undefined) {// outside the scope of the jQuery plugin to// keep track of all dropdownsvar $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出錯。
插件支持HTML元素data-*傳參,也支持初始化傳參。將此js代碼放在bootstrap原本的js代碼后面執行即可。
以上所述是小編給大家介紹的Bootstrap中的Dropdown下拉菜單更改為懸停(hover)觸發,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答