首页 » CSS » CSS中的focus-within伪类选择器

CSS中的focus-within伪类选择器

原文 http://blog.csdn.net/Dear_Mr/article/details/79132286

2018-01-23 02:00:13阅读(281)

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

CSS/: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;
}

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

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹