如何不通过JS代码实现点击改变颜色

前言

希望只通过 CSS 的方法来完成点击改变颜色的需求,这样就不用写冗余的 JS 代码。

第一种 input

通过如下的 DOM 结构:

1
2
3
<div class="father">
<input class="children" />
</div>
1
2
3
.father:focus-within {
background-color: red;
}

但是上面的方案是 <button>,<input>,<select>,<a> 这类可交互元素,是默认存在 focus 事件的,而类似 <div>,<span><table> 这类非交互元素,默认是不能被聚焦的。所以有了第二种方法。

第二种 div

1
2
3
4
5
<div class="g-father">
<!-- 拥有 focus 事件的 .g-children 元素 -->

<div class="g-children" tabindex="-1">Click</div>
</div>

这里为什么是 tabindex="-1" 呢?tabindex 负值表示元素是可聚焦的,但是不能通过键盘导航来访问到该元素。因为我们只需要让元素能够获得 focus 事件,而不需要它真的能够被键盘导航来访问。

1
2
3
.g-father:focus-within {
background: #fc0;
}

问题:需要在点击同样具有 focus 属性的元素才取消选中的颜色。

发现在 FocusEvent 对象中 relatedTarget,为 null 的时候发生在点击空白处。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**

* @description: 点击其他的地方不失焦

* @param {*} e

* @return {*}

* @Date: 2021-12-01 10:14:57

* @Author: David

*/

divBlur(e) {

if (!e.relatedTarget) {

e.target.focus();

}

// console.log(e)

}