Home >Web Front-end >JS Tutorial >Implementation of drop-down menu under Bootstrap framework (code example)
The content this article brings to you is about the implementation of drop-down menus under the Bootstrap framework (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Context menus or hidden/show menu items are often needed when interacting with web pages. Bootstrap provides a switchable, contextual menu by default for displaying a link list. Moreover, the menu display in various interactive states needs to be used in conjunction with the javascript plug-in. This article will introduce the Bootstrap drop-down menu in detail (free course recommendation: bootstrap tutorial)
Usage method
When using the drop-down menu of the Bootstrap framework, The bootstrap.js file provided by the Bootstrap framework must be called. Of course, if you are using the uncompiled version, you can find a file named "dropdown.js" in the js folder, and you can also call this js file
because Bootstrap's component interaction effects all depend on A plug-in written by the jQuery library, so jquery.js must be loaded before using bootstrap.js to produce the effect
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script> <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </body> </html>
Basic usage
When using the drop-down menu component in the Bootstrap framework, it is very important to use the correct structure. If the structure and class name are not used correctly, it will directly affect whether the component can be used normally.
1. Use a name The "dropdown" container wraps the entire drop-down menu element
<div class="dropdown"></div>
2. Use a
<button class="btn dropdown-toggle" type="button" data-toggle="dropdown">
3. Use of drop-down menu items A ul list, and define a class named "dropdown-menu"
<ul class="dropdown-menu" role="menu">
<div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropdown <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> </ul> </div>
4. By setting the .dropup
class for the parent element of the drop-down menu, you can make the menu pop up (the default is to pop up downward)
<div class="dropup"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropup <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> </ul> </div>
Principle Analysis
Drop-down menu component in the Bootstrap framework , its drop-down menu items are hidden by default because the default style of "dropdown-menu" is set to "display:none"; when the user clicks the parent menu item, the drop-down menu will be displayed; when the user clicks again, the drop-down menu Will continue to hide
.dropdown-menu { position: absolute;/*设置绝对定位,相对于父元素p.dropdown*/ top: 100%;/*让下拉菜单项在父菜单项底部,如果父元素不设置相对定位,该元素相对于body元素*/ left: 0; z-index: 1000;/*让下拉菜单项不被其他元素遮盖住*/ display: none;/*默认隐藏下拉菜单项*/ float: left; min-width: 160px; padding: 5px 0; margin: 2px 0 0; font-size: 14px; list-style: none; background-color: #fff; background-clip: padding-box; border: 1px solid #ccc; border: 1px solid rgba(0, 0, 0, .15); border-radius: 4px; -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175); box-shadow: 0 6px 12px rgba(0, 0, 0, .175); }
[Implementation principle]
1. When the Dropdown plug-in is loading the web page, all files with data-toggle= "dropdown" style elements for event binding
2. When the user clicks a link or button with data-toggle="dropdown" style, the javascript event code is triggered
3. javascript The event code adds an .open style to the parent container
4. The .dropdown-menu menu that is hidden by default can be displayed after it has an .open style externally, thereby achieving the expected effect
5. When the user clicks again, the class name "open" in the "p.dropdown" container will be removed again
.open > .dropdown-menu { display: block; }
[Other usages 】
Another interesting usage is that the trigger element can be placed outside the parent container of the menu
However, there are two points to note in this usage
1. To set the id value of the parent container
2. To set the data-toggle attribute and data-target attribute of the trigger element, the data-target attribute value is #id
<button class="btn dropdown-toggle" type="button" data-toggle="dropdown" data-target="#dropdown1">外部触发器</button> <div class="dropdown" id="dropdown1"> <ul class="dropdown-menu" role="menu" aria-labelledby="tutorial"> <li role="presentation"><a href="##">HTML</a></li> <li role="presentation"><a href="##">CSS</a></li> <li role="presentation"><a href="##">javascript</a></li> </ul> </div>
Extension usage
[Separator]
In the Bootstrap framework The drop-down menu provides a drop-down separator line. Assuming that the drop-down menu has two groups, the group can be added by adding an empty
.dropdown-menu .pider { height: 1px; margin: 9px 0; overflow: hidden; background-color: #e5e5e5; }
<li role="separator" class="pider"></li>
<div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropdown <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li><a href="#">Separated link</a></li> </ul> </div>
【Menu Title】
You can add a title to any drop-down menu to indicate a group of actions
<li class="dropdown-header">Dropdown header</li>
.dropdown-header { display: block; padding: 3px 20px; font-size: 12px; line-height: 1.42857143; color: #999; }
<div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropdown <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1"> <li role="presentation" class="dropdown-header">第一部分菜单头部</li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">下拉菜单项</a></li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">下拉菜单项</a></li> <li role="presentation" class="divider"></li> <li role="presentation" class="dropdown-header">第二部分菜单头部</li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">下拉菜单项</a></li> </ul> </div>
【对齐方式】
Bootstrap框架中下拉菜单默认是左对齐,如果想让下拉菜单相对于父容器右对齐时,可以在“dropdown-menu”上添加一个“dropdown-menu-right”类名
.dropdown-menu-right { right: 0; left: auto; }
由于
display: inline-block; margin-left: 60px;
<div class="dropdown" style="display: inline-block;margin-left: 60px;"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropdown <span class="caret"></span> </button> <ul class="dropdown-menu dropdown-menu-right" role="menu" aria-labelledby="dropdownMenu1"> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">下拉菜单项</a></li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">下拉菜单项</a></li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">下拉菜单项</a></li> <li role="presentation" class="divider"></li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">下拉菜单项</a></li> </ul> </div>
【菜单项状态】
下拉菜单项的默认的状态有悬浮状态(:hover)和焦点状态(:focus)
.dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus { color: #262626; text-decoration: none; background-color: #f5f5f5; }
下拉菜单项除了上面两种状态,还有当前状态(.active)和禁用状态(.disabled)。这两种状态使用方法只需要在对应的菜单项上添加对应的类名
<div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropdown <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1"> <li role="presentation" class="active"><a role="menuitem" tabindex="-1" href="#">下拉菜单项</a></li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">下拉菜单项</a></li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">下拉菜单项</a></li> <li role="presentation" class="divider"></li> <li role="presentation" class="disabled"><a role="menuitem" tabindex="-1" href="#">下拉菜单项</a></li> </ul> </div>
JS触发
和模态弹出窗一样,Bootstrap框架中的下拉菜单也支持JavaScript方法触发下拉菜单显示。但是,要特点注意的是,即使使用JS触发,也不能去掉触发元素的data-toggle="dropdown"
<div class="dropdown"> <button class="btn dropdown-toggle" data-toggle="dropdown" type="button">触发器</button> <ul class="dropdown-menu" role="menu" aria-labelledby="tutorial"> <li role="presentation"><a href="##">HTML</a></li> <li role="presentation"><a href="##">CSS</a></li> <li role="presentation"><a href="##">javascript</a></li> </ul> </div> <script> ;$(function(){ $('.dropdown-toggle').dropdown() }); </script>
【toggle】
和Modal一样,dropdown也接收字符串作为参数进行传递,参数可以是"toggle"
但是,这非常不好用。每次单击都要两次toggle,就会一直是一个不变的状态。所以,一般情况下,使用不带参数的方法。就算需要使用参数“toggle”,也建议使用jQuery的one方法
$(".dropdown-toggle").one("click",function(){ $(this).dropdown("toggle"); })
【事件订阅】
与Modal类似,下拉菜单支持4种类型的事件订阅,分别对应下拉菜单的弹出前、弹出后、关闭前、关闭后
show.bs.dropdown 在show方法调用时立即触发(尚未显示之前) shown.bs.dropdown 在下拉菜单完全显示给用户之后(并且等CSS动画完成之后)触发 hide.bs.dropdown 在hide方法调用时(但还未关闭隐藏)立即触发 hidden.bs.dropdown 在下拉菜单完全隐藏之后(并且等CSS动画完成之后)触发
<div class="dropdown"> <button class="btn dropdown-toggle" data-toggle="dropdown" type="button">触发器</button> <ul class="dropdown-menu" role="menu" aria-labelledby="tutorial"> <li role="presentation"><a href="##">HTML</a></li> <li role="presentation"><a href="##">CSS</a></li> <li role="presentation"><a href="##">javascript</a></li> </ul> </div> <script> ;$(function(){ $('.dropdown').on('show.bs.dropdown',function(){ $('.dropdown-toggle').html('关闭'); }); $('.dropdown').on('hide.bs.dropdown',function(){ $('.dropdown-toggle').html('打开'); }); }); </script>
JS源码
【1】IIFE
使用立即调用函数,防止插件内代码外泄,从而形成一个闭环,并且只能从jQuery的fn里进行扩展
+function ($) { //使用es5严格模式 'use strict'; //}(window.jQuery);
【2】初始设置
//弹出下拉菜单时的蒙版样式 var backdrop = '.dropdown-backdrop' //dropdown触发元素的自定义属性 var toggle = '[data-toggle="dropdown"]' var Dropdown = function (element) { //插件类函数定义,一旦触发,就在click事件上绑定toggle,所以不能再用自定义代码进行toggle了 $(element).on('click.bs.dropdown', this.toggle) } //版本号为'3.3.7' Dropdown.VERSION = '3.3.7'
【3】插件核心代码
//获取下拉菜单的父元素容器 function getParent($this) { //获取触发元素的'data-target'特性值,表示下拉菜单的父元素容器的选择器 var selector = $this.attr('data-target') //如果触发元素没有设置'data-target' if (!selector) { //获取触发元素的'href'特性值,表示下拉菜单的父元素容器的选择器 selector = $this.attr('href') //该值是所弹出元素的id值 selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } //通过选择器,来获取下拉菜单的父元素容器 var $parent = selector && $(selector) //如果找到,说明触发元素确实在下拉菜单外部,则返回找到的下拉菜单的父元素容器即可 //如果没有找到,说明触发元素在下拉菜单内部,则返回它的直接父级元素 return $parent && $parent.length ? $parent : $this.parent() } //关闭所有的下拉菜单 function clearMenus(e) { //如果点击的是鼠标右键,则直接返回 if (e && e.which === 3) return //删除用于移动设备的蒙版 $(backdrop).remove() //根据选择器,遍历所有的dropdown标记,然后全部关闭 $(toggle).each(function () { var $this = $(this) var $parent = getParent($this) var relatedTarget = { relatedTarget: this } //如果下拉菜单的父元素容器没有open类名,则直接返回 if (!$parent.hasClass('open')) return //如果触发了鼠标单击事件,并且鼠标事件的目标元素是input或textarea,则直接返回 if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return //关闭前,触发hide事件 $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) //如果阻止了默认行为,则直接返回 if (e.isDefaultPrevented()) return $this.attr('aria-expanded', 'false') //关闭后,触发hidden事件 $parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget)) }) } //控制下拉菜单的打开、关闭操作 Dropdown.prototype.toggle = function (e) { var $this = $(this) //如果有禁用标记,则不处理 if ($this.is('.disabled, :disabled')) return //获取下拉菜单的父元素容器 var $parent = getParent($this) //判断下拉菜单的父元素容器是否有open样式 var isActive = $parent.hasClass('open') //关闭所有的下拉菜单 clearMenus() //如果是,在clearMenus阶段已经关闭了,所以不需要再次关闭 //如果不是,说明默认是关闭状态,则需要展开下拉菜单 if (!isActive) { //如果是移动设置,则使用dropdown-backdrop样式,因为移动设备不支持click单击委托 if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { $(document.createElement('div')) .addClass('dropdown-backdrop') .insertAfter($(this)) .on('click', clearMenus) } var relatedTarget = { relatedTarget: this } //展开下拉菜单前,触发show事件 $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) //如果阻止了默认行为,则直接返回 if (e.isDefaultPrevented()) return $this //设置focus样式 .trigger('focus') .attr('aria-expanded', 'true') $parent //设置open样式 .toggleClass('open') //展开下拉菜单后,触发shown事件 .trigger($.Event('shown.bs.dropdown', relatedTarget)) } return false } //利用键盘控制下拉菜单 Dropdown.prototype.keydown = function (e) { //如果按键不是esc、或上下方向键、或空格键,或者目标元素是input或textarea控件,则忽略处理 if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return var $this = $(this) //阻止默认行为及冒泡 e.preventDefault() e.stopPropagation() //如果有禁用标记,则不做处理 if ($this.is('.disabled, :disabled')) return //获取下拉菜单的父元素容器 var $parent = getParent($this) //判断父元素是否有open样式 var isActive = $parent.hasClass('open') //如果有open样式并且按键不是向下箭头,或者没有open样式并且按键是向下箭头,也打开下拉菜单 if (!isActive && e.which != 27 || isActive && e.which == 27) { //如果按下向下箭头,则给触发元素加上焦点 if (e.which == 27) $parent.find(toggle).trigger('focus') //触发单击事件 return $this.trigger('click') } //返回可以利用箭头选择的下拉菜单项 //必须是可见的a链接,并且不包括分隔符 var desc = ' li:not(.disabled):visible a' var $items = $parent.find('.dropdown-menu' + desc) //如果没有,则不做处理 if (!$items.length) return //找出当前处理焦点状态的第一个下拉菜单项的索引 var index = $items.index(e.target) //按向上箭头,index-1 if (e.which == 38 && index > 0) index-- //按向下箭头,index+1 if (e.which == 40 && index < $items.length - 1) index++ //当index为-1时,置为0 if (!~index) index = 0 //给所选择的菜单项设置焦点 $items.eq(index).trigger('focus') }
【4】jQuery插件定义
function Plugin(option) { //根据选择器,遍历所有符合规则的元素 return this.each(function () { var $this = $(this) //获取自定义属性bs.dropdown的值 var data = $this.data('bs.dropdown') //如果值不存在,则将Dropdown实例设置为bs.dropdown值 if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) //如果option传递了string,则表示要执行某个方法 if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.dropdown //保留其他库的$.fn.modal代码(如果定义的话),以便在noConflict之后可以继续使用该老代码 $.fn.dropdown = Plugin //重设插件构造器,可以通过该属性获取插件的真实类函数 $.fn.dropdown.Constructor = Dropdown
【5】防冲突处理
$.fn.dropdown.noConflict = function () { //恢复以前的旧代码 $.fn.dropdown = old //将$.fn.dropdown.noConflict()设置为Bootstrap的Dropdown插件 return this }
【6】绑定触发事件
$(document) //为声明式的HTML绑定单击事件,在单击以后先关闭所有的下拉菜单 .on('click.bs.dropdown.data-api', clearMenus) //如果内部有form元素,则阻止冒泡,不做其他处理 .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) //绑定单击事件,执行toggle()方法 .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) //绑定键盘keydown事件,执行keydown()方法 .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown) //为dropdown-menu绑定键盘keydown事件,执行keydown()方法 .on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)
The above is the detailed content of Implementation of drop-down menu under Bootstrap framework (code example). For more information, please follow other related articles on the PHP Chinese website!