CSS中的focus-within伪类选择器

:focus-within很容易让人联想到focus,区别就在于focus是对于当前元素,而:focus-within则是对于当前对象和当前对象子元素

MDN: The :focus-within CSS pseudo-class represents an element that has received focus or contains an element that has received focus. In other words, it represents an element that is itself matched by the :focus pseudo-class or has a descendant that is matched by :focus.

那么这个伪类有什么作用呢?

This selector is useful, to take a common example, for highlighting an entire form container when the user focuses on one of its input fields.

相关的例子:

表单交互时背景高亮

<form class="user-form">
  <label>账号: <input class="common-input" type="text" name="id"></label><br>
  <label>密码: <input class="common-input" type="password" name="password"></label>
</form>
.user-form {
  width: 300px;
  height: 100px;
  border: 1px solid #EDEDED;
  color: #000;
  padding: 4px;
}
.user-form:focus-within {
  background: #EDEDED;
  color: black;
}
.user-form label {
  display: inline-block;
  margin: 6px 10px;
}
.common-input {
  margin: 4px;
}

表单输入时,页面上出来表单其他元素不可见

<h2>表单输入页面</h2>
<form class="user-form">
  <label>账号: <input class="common-input" type="text" name="id"></label><br>
  <label>密码: <input class="common-input" type="password" name="password"></label>
</form>
.user-form {
  width: 300px;
  height: 100px;
  border: 1px solid #EDEDED;
  color: #000;
  padding: 4px;
  outline: 2000px solid hsla(0, 0%, 100%, 0);
  transition: outline .2s;
  position: relative;
  z-index: 1;
}
.user-form:focus-within {
  outline: 2000px solid hsla(0, 0%, 100%, 1);   
}
.user-form label {
  display: inline-block;
  margin: 6px 10px;
}
.common-input {
  margin: 4px;
}

带计数文本域高亮

<div class="container-textarea">
  <textarea id="text" maxlength="200" rows="6"></textarea>
  <label for="text" class="label-count">0/200</label>
</div>
.container-textarea {
  max-width: 280px;
  border: 1px solid #d0d0d5;
  border-radius: 5px;
  background-color: #fff;
  padding-bottom: 24px;
  overflow: hidden;
  position: relative;
}
.label-count {
  position: absolute;
  font-size: 12px;
  line-height: 16px;
  bottom: 5px;
  right: 10px;
  color: #999;
}
.container-textarea textarea {
  display: block;
  width: 100%;
  padding: 7px 9px;
  border: 0;
  background: none;
  box-sizing: border-box;
  outline: 0;
  resize: none;
}
.container-textarea:focus-within {
  border-color: #00a5e0;
}

当然它还是有其他应用场景的,欢迎补充^_^

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值