学透CSS-:focus-within 仿掘金登录小人动画

3,355 阅读1分钟

大家好,我是半夏👴,一个刚刚开始写文的沙雕程序员.如果喜欢我的文章,可以关注➕ 点赞 👍 加我微信:frontendpicker,一起学习交流前端,成为更优秀的工程师~关注公众号:搞前端的半夏,了解更多前端知识! 点我探索新世界!

兼容性

作为:focus的好兄弟,在兼容性上也还是不错的。主流的浏览器基本都已经支持这个属性。 image.png

:focus-within 和 :focus 的区

:focus-within 表示一个元素自身获取焦点,以及子元素获取焦点后的效果。

:focus 表示元素自身获取到焦点后的效果。

示例

定义一个form表单,背景颜色是green。

form{          
    padding: 50px;
    background-color:green ;
}
<form action="">
    <input type="text">
</form>

image.png

定义获取焦点后的效果

form:focus-within{
    background-color: aqua;
}
input:focus{
    background-color: red;
}

当input标签获取到焦点后,背景颜色变成了red,同时form的背景颜色变成aqea image.png

应用场景- form表单输入(掘金登录页面)

掘金在登录输入密码的时候,这个小人会挡住自己的眼睛,有很多作者用各种方法实现这个效果,:focu-within有同样可以实现这个效果。 image.png

首先实现登陆前的画面(比较丑)

<div class="login">
  <form action="">
    <div class="panfish"></div>
    <div><label for=""> 账号</label> <input type="text" /></div>
    <div><label for=""> 密码</label> <input type="text" /></div>
  </form>
</div>

.login {
    position: relative;
    padding: 2rem;
    width: 20rem;
    font-size: 1.167rem;
    background-color: #fff;
    border-radius: 2px;
    box-sizing: border-box;
  }
  .panfish {
    background: url(https://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/ad7fa76844a2df5c03151ead0ce65ea6.svg);
    z-index: 1;
    padding-top: 50px;
    width: 20rem;
    height:50px;
    position: absolute;
    background-repeat: no-repeat;

    top: -60px;
  }
  input:focus {
    background-color: red;
  }

image.png

使用:fous-within

form:focus-within > .panfish {
background: url(https://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/4f6f6f316cde4398d201cd67e44ddea3.svg);
background-repeat: no-repeat;

}

获取焦点后的效果

image.png

GIF

focuswithin.gif