有趣的CSS - 输入框选中交互动效

本文详细介绍了如何使用HTML和CSS创建一个具有实时交互效果的输入框,通过CSS伪类和required属性实现,适用于登录和表单提交场景,提升用户体验。
摘要由CSDN通过智能技术生成

页面效果

此效果主要使用 css 伪选择器配合 html5 required 属性来实现一个简单的输入框的交互效果。

此效果可适用于登录页入口、小表单提交等页面,增强用户实时交互体验。


核心代码部分,简要说明了写法思路;完整代码在最后,可直接复制到本地运行。

核心代码

html代码

<label>
  <input type="text" required>
  <span>用户名</span>
</label>

页面主要使用 labelinput 标签,注意 input 中使用 required 属性,来判断 input 是否为空。

css代码

label{
  width: 240px;
  position: relative;
  display: flex;
  align-items: center;
}
input{
  width: 240px;
  height: 32px;
  line-height: 32px;
  padding: 0 10px;
  border: 2px solid transparent;
  border-bottom-color: #333;
  background-color: transparent;
  box-sizing: border-box;
  transition: all 0.3s;
  font-size: 14px;
  color: #333;
}
span{
  position: absolute;
  font-size: 14px;
  color: #999;
  left: 10px;
  cursor: text;
  z-index: 1;
  transition: all 0.3s;
}
label:hover input,input:focus{
  border-color: blue;
  border-radius: 8px;
}
input:focus+span,input:valid+span{
  transform: translateY(-32px);
}

使用选择器 :hover:foucus 来获取鼠标状态,根据不同鼠标的不同状态来设置样式以及过渡效果,使用 :valid 来验证 input 值。

完整代码

html页面

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">
    <title>输入框选中交互动效</title>
  </head>
  <body>
    <div class="app">
      <label>
        <input type="text" required>
        <span>用户名</span>
      </label>
    </div>
  </body>
</html>

css样式

.app{
  width: 100%;
  height: 100vh;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
input{
  list-style: none;
  outline-style: none;
}
label{
  width: 240px;
  position: relative;
  display: flex;
  align-items: center;
}
input{
  width: 240px;
  height: 32px;
  line-height: 32px;
  padding: 0 10px;
  border: 2px solid transparent;
  border-bottom-color: #333;
  background-color: transparent;
  box-sizing: border-box;
  transition: all 0.3s;
  font-size: 14px;
  color: #333;
}
span{
  position: absolute;
  font-size: 14px;
  color: #999;
  left: 10px;
  cursor: text;
  z-index: 1;
  transition: all 0.3s;
}
label:hover input,input:focus{
  border-color: blue;
  border-radius: 8px;
}
input:focus+span,input:valid+span{
  transform: translateY(-32px);
}

页面效果

以上就是全部代码以及简单的写法思路,希望你喜欢这个交互输入框。


[1] 原文阅读

我是 Just,这里是「设计师工作日常」,求点赞求关注!!!

  • 34
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

设计师工作日常

请我炫个饼🫓

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值