在 Bootstrap 5 菜单中,在第一项中按向上箭头键或在最后一项中按向下允许键不会执行任何操作。
如何制作箭头(如果在第一项中按下则移动到菜单中的最后一项)和向下箭头(如果在最后一项中按下则移动到第一项)就像在普通 Windows 桌面应用程序菜单中一样?
重现打开的页面
<div class="btn-group">
<button type="button" class="btn btn-danger dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
Action
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#"><u>A</u>ction</a></li>
<li><a class="dropdown-item" href="#">A<u>n</u>other action</a></li>
<li><a class="dropdown-item" href="#"><u>S</u>omething else here</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="#">S<u>e</u>parated link</a></li>
</ul>
</div>
https://jsfiddle.net/b6or2s5e/
打开操作菜单。在第一个菜单行中按向上箭头或在最后一个菜单行中按向下箭头不起作用
没有这方面的 API。我正在捕获事件
keydown
并聚焦第一个/最后一个可见的 .menu-item
.
addEventListener('keydown', function(ev) {
const SELECTOR_VISIBLE_ITEMS = '.dropdown-item:not(.disabled):not(:disabled)'
var elem = ev.target;
var menu = elem.closest(".dropdown-menu")
if (menu) {
var visibleChildren = [...menu.querySelectorAll(SELECTOR_VISIBLE_ITEMS)]
var length = visibleChildren.length;
var index = visibleChildren.indexOf(elem);
if (length) {
var first = visibleChildren[0]
var last = visibleChildren[length - 1]
if (ev.key === 'ArrowDown' && index == length - 1) {
first.focus();
ev.preventDefault()
ev.stopPropagation();
return;
}
if (ev.key === 'ArrowUp' && index == 0) {
last.focus();
ev.preventDefault()
ev.stopPropagation();
return;
}
}
}
// must use capture = true
}, true)
body {
padding: 10px;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"></link>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<!-- Example single danger button -->
<div class="btn-group">
<button type="button" class="btn btn-danger dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
Action
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#"><u>A</u>ction</a></li>
<li><a class="dropdown-item" href="#">A<u>n</u>other action</a></li>
<li><a class="dropdown-item" href="#"><u>S</u>omething else here</a></li>
<li>
<hr class="dropdown-divider">
</li>
<li><a class="dropdown-item" href="#">S<u>e</u>parated link</a></li>
</ul>
</div>