我正在尝试使用slideDown效果实现一个简单的下拉列表。为了构建这种效果,我使用了一个应用于transition
属性的CSS height
。
问题是,如果我按下Tab ↹
键,下拉列表中的任何可定位元素(制表位)将被定位,即使它被隐藏,因为我没有使用display: none
。
这是代码:
const button = document.getElementById('button');
const dropdown = document.getElementById('dropdown');
dropdown.style.setProperty('height', 'auto', 'important');
dropdown.style.setProperty('height', dropdown.clientHeight + 'px');
button.addEventListener('click', function(e) {
e.target.classList.toggle('active');
e.target.nextElementSibling.classList.toggle('active');
});
#dropdown {
overflow: hidden;
transition: height 330ms linear;
background-color: lightgrey;
height: 200px;
}
#dropdown:not(.active) {
height: 0 !important;
}
#dropdown.active {
visibility: visible;
}
<button id="button">Click me!</button>
<div id="dropdown">
<a href="#">I should not be accessible with tab when dropdown is hidden</a>
</div>
<div id="info">This link will be focused after three tabs, instead of two: <a href="#">Tab me!</a></div>
我尝试使用transitionend
事件稍微修改代码,以便在转换结束时添加和删除display: none
,从而使下拉列表中的任何可定位元素无法自定义,但这会与转换的起始动画混淆。
看到:
const button = document.getElementById('button');
const dropdown = document.getElementById('dropdown');
dropdown.style.setProperty('height', 'auto', 'important');
dropdown.style.setProperty('height', dropdown.clientHeight + 'px');
dropdown.classList.add('hidden');
button.addEventListener('click', function(e) {
if (!e.target.classList.contains('active'))
dropdown.classList.remove('hidden');
e.target.classList.toggle('active');
e.target.nextElementSibling.classList.toggle('active');
});
dropdown.addEventListener('transitionend', function(e) {
dropdown.classList.add('hidden');
});
#dropdown {
overflow: hidden;
transition: height 330ms linear;
background-color: lightgrey;
height: 200px;
}
#dropdown:not(.active) {
height: 0 !important;
}
#dropdown.active {
visibility: visible;
}
a {
display: block; /* so it doesn't move when dropdown is hidden */
}
.hidden {
display: none;
}
<button id="button">Click me!</button>
<div id="dropdown">
<a href="#">I should not be accessible with tab when dropdown is hidden</a>
</div>
<div id="info">This link will now be focused after <strong>two</strong> tabs, as expected: <a href="#">Tab me!</a></div>
尝试将属性“tabindex”设置为-1,这样可以防止使用制表符选择链接。当下拉列表处于活动状态时,您也可以使用JS删除此属性
您可以修改元素的tabIndex(-1以使其无法定位,非常高的数字以使其最后定位)。 How to ignore HTML element from tabindex?