bootstrap中將選單改為滑鼠滑過(bootstrap-dropdown-hover外掛)
出處:https://www.cnblogs.com/EnderH/archive/2016/04/09/5371712.html
bootstrap的下拉元件,需要點選click時,方可展示下拉列表。因此對於喜歡簡單少操作的大家來說,點選一下多少帶來不便,因此,引入hover監聽,滑鼠經過自動展示下拉框。其實在bootstrap導航條當中dropdown元件用得特別頻繁啦!
如何實現這個hover事件呢,其實在dropdown元件的點選事件的基礎上很好完成的。細心者可以發現,下拉框出現時,其父級會有一個open的class屬性。我們只需要監聽hover事件時,給父級增加或刪除open類就可以了。
boostrap-hover-dropdown.js外掛,託管在github
下面是完整的js外掛程式碼:
123456789101112131415161718192021222324252627282930313233343536373839404142 | // bootstrap響應式導航條<br data-filtered="filtered">;(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-*屬性:
1 | data-hover="dropdown" |
完整的HTML元素程式碼:
1 | < a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown"></ a > |
可以通過資料屬性設定選項,也可以通過data-delay和data-close-others來設定選項
1 | < a href="#" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="1000" data-close-others="false"></ a > |
當然,還有最簡單的方法,那就是用css的hover控制
1 | .nav> li:hover .dropdown-menu { display : block ;} |
這樣一句程式碼也能實現想要的hover效果,只不過如果在hover的時候點選元件,再去hover另一個元件就會出現如下效果: