侧边栏壁纸
博主头像
MicroMatrix博主等级

曲则全,枉则直,洼则盈,敝则新,少则得,多则惑。是以圣人抱一为天下式。不自见,故明;不自是,故彰;不自伐,故有功;不自矜,故长。夫唯不争,故天下莫能与之争。古之所谓“曲则全”者,岂虚言哉!诚全而归之。

  • 累计撰写 80 篇文章
  • 累计创建 21 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

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

蜗牛
2022-03-27 / 0 评论 / 0 点赞 / 5 阅读 / 3297 字 / 正在检测是否收录...

前言

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

第一种 input

通过如下的 DOM 结构:

<div class="father">

	<input class="children" />

</div>
.father:focus-within {

	background-color: red;
}

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

第二种 div

<div class="g-father">

<!-- 拥有 focus 事件的 .g-children 元素 -->

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

</div>

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

.g-father:focus-within {

background: #fc0;

}

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

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

/**

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

* @param {*} e

* @return {*}

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

* @Author: David

*/

divBlur(e) {

	if (!e.relatedTarget) {
	
		e.target.focus();
	
	}

	// console.log(e)

}
0

评论区