这是我们将要构建的内容:
HTML
本质上,我们希望将两组不同的 Bootstrap 控件和样式结合起来:Dropdowns 和 Checkboxes。在每个li 内部,我们将使用label 代替a 元素,以便我们可以wrap the checkbox in a label 并使整行可点击。
<ul class="dropdown-menu checkbox-menu allow-focus">
<li >
<label>
<input type="checkbox"> Cheese
</label>
</li>
</ul>
CSS
我们可以窃取一些通常应用于.dropdown-menu li a 的样式,输入并将它们应用于我们的标签选项。我们将使标签占据容器的整个宽度并修复一些标签/复选框对齐问题。此外,我们将为.active 和:hover 添加样式。
.checkbox-menu li label {
display: block;
padding: 3px 10px;
clear: both;
font-weight: normal;
line-height: 1.42857143;
color: #333;
white-space: nowrap;
margin:0;
transition: background-color .4s ease;
}
.checkbox-menu li input {
margin: 0px 5px;
top: 2px;
position: relative;
}
.checkbox-menu li.active label {
background-color: #cbcbff;
font-weight:bold;
}
.checkbox-menu li label:hover,
.checkbox-menu li label:focus {
background-color: #f5f5f5;
}
.checkbox-menu li.active label:hover,
.checkbox-menu li.active label:focus {
background-color: #b8b8ff;
}
JavaScript
其他一些管理工作,我们将在每个列表项上手动保留一个 .active 类标志,以对应于该项目是否被选中,以便我们可以适当地设置它的样式。
$(".checkbox-menu").on("change", "input[type='checkbox']", function() {
$(this).closest("li").toggleClass("active", this.checked);
});
我们还希望通过阻止事件冒泡来允许菜单stay open on internal click events 来允许多项选择
$(document).on('click', '.allow-focus', function (e) {
e.stopPropagation();
});
堆栈片段中的演示
$(".checkbox-menu").on("change", "input[type='checkbox']", function() {
$(this).closest("li").toggleClass("active", this.checked);
});
$(document).on('click', '.allow-focus', function (e) {
e.stopPropagation();
});
body {
padding: 15px;
}
.checkbox-menu li label {
display: block;
padding: 3px 10px;
clear: both;
font-weight: normal;
line-height: 1.42857143;
color: #333;
white-space: nowrap;
margin:0;
transition: background-color .4s ease;
}
.checkbox-menu li input {
margin: 0px 5px;
top: 2px;
position: relative;
}
.checkbox-menu li.active label {
background-color: #cbcbff;
font-weight:bold;
}
.checkbox-menu li label:hover,
.checkbox-menu li label:focus {
background-color: #f5f5f5;
}
.checkbox-menu li.active label:hover,
.checkbox-menu li.active label:focus {
background-color: #b8b8ff;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button"
id="dropdownMenu1" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="true">
<i class="glyphicon glyphicon-cog"></i>
<span class="caret"></span>
</button>
<ul class="dropdown-menu checkbox-menu allow-focus" aria-labelledby="dropdownMenu1">
<li >
<label>
<input type="checkbox"> Cheese
</label>
</li>
<li >
<label>
<input type="checkbox"> Pepperoni
</label>
</li>
<li >
<label>
<input type="checkbox"> Peppers
</label>
</li>
</ul>
</div>