首页 > 解决方案 > 单击 div 时避免 :focus 样式(仅在 tab 键上)

问题描述

在下面的最小示例中,我有一个 div 作为按钮。它有一个 tabindex,所以如果我使用 tab 键并进入元素,.with-focus就会应用类的样式。到目前为止,一切都很好。

.with-focus但是当用鼠标点击按钮时,我也得到了类的风格。这就是我想要的。有没有可能避免?

.with-focus[tabindex]:focus {
	outline: 5px solid green;
}

.btn {
  background-color: #eee;
  border: 1px solid #ddd;
  cursor: pointer;
  height: 50px;
  text-align: center;
  width: 200px;
}
<div class="btn with-focus" tabindex="0" onclick="console.log('clicked')">
  Button
</div>

标签: htmlcss

解决方案


我认为您可以使用 :active 子状态,尝试在 :focus 选择器之后添加它

.with-focus[tabindex]:active {
  outline: 0;
}

密码笔


推荐阅读