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另一個組件就會出現如下效果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM