This article will give you a detailed introduction to the drop-down menu in Bootstrap. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
When interacting with web pages, context menus or hidden/show menu items are often required. 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. [Related recommendations: "bootstrap Tutorial"]
When using the drop-down menu of the Bootstrap framework, you must call the drop-down menu provided by the Bootstrap framework bootstrap.js file. 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 have an 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>
When using the Bootstrap framework When using a drop-down menu component, it is very important to use its structure correctly. If the structure and class name are not used correctly, it will directly affect whether the component can be used normally
1. Use a container named "dropdown" 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 a ul list for the drop-down menu item, and define a class name "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 down)
<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>
The drop-down menu component in the Bootstrap framework, its drop-down menu items are hidden by default because the "dropdown-menu" default style is set to "display:none"; when the user clicks When the parent menu item is selected, the drop-down menu will be displayed; when the user clicks again, the drop-down menu will continue to be hidden
.dropdown-menu { position: absolute;/*设置绝对定位,相对于父元素div.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. The Dropdown plug-in is loaded when the web page is loaded , event binding for all elements with data-toggle="dropdown" style
2. When the user clicks a link or button with data-toggle="dropdown" style, the javascript event code is triggered
3. Add an .open style to the parent container in the javascript event code
4. The .dropdown-menu menu that is hidden by default can be displayed after it has an .open style externally. To achieve 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 usage]
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. Set the parent The id value of the container
2. 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>
[Separator]
The drop-down menu in the Bootstrap framework provides a drop-down separator. Assuming that the drop-down menu has two groups, then the group and the group You can add a drop-down divider by adding an empty
.dropdown-menu .divider { height: 1px; margin: 9px 0; overflow: hidden; background-color: #e5e5e5; }
<li role="separator" class="divider"></li>
【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>
【Alignment】
The drop-down menu in the Bootstrap framework is left aligned by default. If you want the drop-down menu to be right-aligned relative to the parent container, you can add a "dropdown-menu-right" class name to "dropdown-menu"
.dropdown-menu-right { right: 0; left: auto; }
Since
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>
[Menu item status]
下拉菜单项的默认的状态有悬浮状态(: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>
和模态弹出窗一样,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>
【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 A simple introduction to drop-down menus in Bootstrap. For more information, please follow other related articles on the PHP Chinese website!