如何不通过JS代码实现点击改变颜色
前言
希望只通过 CSS 的方法来完成点击改变颜色的需求,这样就不用写冗余的 JS 代码。
第一种 input
通过如下的 DOM 结构:
1 | <div class="father"> |
1 | .father:focus-within { |
但是上面的方案是 <button>,<input>,<select>,<a>
这类可交互元素,是默认存在 focus 事件的,而类似 <div>,<span>
和 <table>
这类非交互元素,默认是不能被聚焦的。所以有了第二种方法。
第二种 div
1 | <div class="g-father"> |
这里为什么是 tabindex="-1"
呢?tabindex
负值表示元素是可聚焦的,但是不能通过键盘导航来访问到该元素。因为我们只需要让元素能够获得 focus 事件,而不需要它真的能够被键盘导航来访问。
1 | .g-father:focus-within { |
问题:需要在点击同样具有 focus 属性的元素才取消选中的颜色。
发现在 FocusEvent
对象中 relatedTarget
,为 null
的时候发生在点击空白处。
1 | /** |