在Bootstrap 4中,可以使用以下方法来实现自动关闭下拉菜单上的子菜单:
<a>
标签上添加data-toggle="dropdown"
属性,同时在子菜单的<a>
标签上添加data-toggle="dropdown"
属性。这样点击子菜单时,父级下拉菜单会自动关闭。示例代码:
<div class="dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
下拉菜单
</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">子菜单1</a>
<a class="dropdown-item" href="#">子菜单2</a>
<a class="dropdown-item" href="#">子菜单3</a>
</div>
</div>
示例代码:
<div class="dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
下拉菜单
</a>
<div class="dropdown-menu" id="dropdown-menu">
<a class="dropdown-item" href="#">子菜单1</a>
<a class="dropdown-item" href="#">子菜单2</a>
<a class="dropdown-item" href="#">子菜单3</a>
</div>
</div>
<script>
var dropdownMenu = document.getElementById('dropdown-menu');
var dropdownToggle = document.querySelector('.dropdown-toggle');
dropdownMenu.addEventListener('click', function(event) {
event.stopPropagation();
});
dropdownToggle.addEventListener('click', function() {
if (dropdownMenu.classList.contains('show')) {
dropdownMenu.classList.remove('show');
} else {
dropdownMenu.classList.add('show');
}
});
document.addEventListener('click', function() {
dropdownMenu.classList.remove('show');
});
</script>
以上是在Bootstrap 4中实现自动关闭下拉菜单上的子菜单的方法。这样可以提升用户体验,使得在点击子菜单时,父级下拉菜单能够自动关闭。
领取专属 10元无门槛券
手把手带您无忧上云