【问题标题】:Dropdown menu elements lose focus on tab下拉菜单元素失去对选项卡的关注
【发布时间】:2018-08-25 13:30:20
【问题描述】:

我的下拉菜单按钮在悬停时打开 (CSS),但在选项卡上无法访问其内容。

在按钮选项卡上,下拉菜单在下一个选项卡上打开,按下它会跳过菜单的所有内容,将其关闭并继续转到页面上的下一个焦点元素。

我需要能够浏览菜单。这来自我的反应组件:

<div className="dropdown" 
        tabIndex="0"
        role="navigation">
          <button className="dropBtn" tabIndex="0" role="menu" type="button" aria-expanded="false" aria-controls="navbar">
            <i className="hover">Places</i>
          </button>
          <div tabIndex="0" className="dropdown-content">
          <div tabIndex='0' className='filter'>
            <input 
              className='input'
              tabIndex="0"
              type="text"
              placeholder="Search your place"
              value={this.props.query}            
              onChange={e => this.props.handleUpdateQuery(e.target.value)}/>
              </div>
             {/* <div className="search-places-results"> */}
             <ul className='listOfPlaces' 
             role="menubar">
              {this.props.filteredPlaces.map((item)=>{
                return <li item={item} 
                tabIndex="0"
                role="menuitem"
                items={this.props.places} 
                key={item.id}
                onClick={(e)=>{this.props.onItemClick(e, item.id)}}>
                {item.name}</li>
              })}
             </ul>
            {/* </div> */}
          </div>
        </div> 

CSS:

.dropdown-content .filter:hover,
.dropdown-content .filter:focus,
.dropdown-content ul li:hover,
.dropdown-content ul li:focus {
  background-color: rgb(41, 160, 240);
}

.dropdown:hover .dropdown-content,
 .dropdown:focus .dropdown-content {
  display: block;
}

This is how it opens on tab press

【问题讨论】:

  • 您可以添加屏幕截图来说明按钮选项卡上的行为吗?谢谢

标签: javascript css reactjs drop-down-menu


【解决方案1】:

如果不运行它,我在这里看到了几种可能性。首先,我不希望制表符起作用,因为您给了它们所有相同的tabindex。请参阅您的 map 函数,该函数将硬值零分配给所有列表元素。 map 有第二个参数可以传递,它是一个索引。使用它来生成标签索引。

[1, 2, 3].map((x, i) => console.log(i))

其次,您没有将标签索引附加到锚点。这会产生一个 a11y 问题。尝试将menuitemlink aria 角色添加到您的列表项中。正如 MDN 所建议的,使用原生锚元素可能是您最好的选择。 https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_link_role

【讨论】:

  • 非常感谢!
  • 如果这解决了您的问题,请接受我的回答。如果你喜欢,你也可以投票。 :)
【解决方案2】:

为了解决这个问题,我使用了 focus:within :

.dropdown:focus-within .dropdown-content {
  display: block
}

【讨论】:

  • 很遗憾,:focus-within 伪选择器在 IE 和当前版本的 Edge 中不起作用。
猜你喜欢
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多