输入框提示文字跳动效果

1,670 阅读3分钟

这是我参与8月更文挑战的第18天,活动详情查看:8月更文挑战

作者:battleKing
仓库:GithubCodePen
博客:CSDN掘金
反馈邮箱:myh19970701@foxmail.com
特别声明:原创不易,未经授权不得转载或抄袭,如需转载可联系笔者授权

背景

我们在设置表单时,一般都要设置一些 提示文字 搭配 输入框告知用户这里输入什么内容,此时根据提示文字的位置,我们一般有三种设计方案。

  1. 使用placeholder = "请输入用户名"提示文字 设置在 输入框里面

    • 优点:节约空间
    • 缺点:当我们点击输入框,想要输入文字时,提示文字会消失,用户体验差 获得输入框焦点前.PNG 简单提示.png 获得输入框焦点后.PNG 简单提示文字2.jpg
  2. 使用一个 <label> 用户名 </label>提示文字 设置在 输入框的左边输入框的上面

    • 优点:提示文字清晰
    • 缺点:占用空间大

label提示.png

  1. 使用一个 <label> 用户名 </label>提示文字 设置在 输入框里面
    • 优点:当我们点击输入框,想要输入文字时,提示文字波浪式上移,用户体验好
    • 缺点:占用空间大 获得输入框焦点前.PNG image.png

获得输入框焦点后.PNG image.png

因为 第三种 兼顾了 时尚感实用性,所以在很多新兴企业里面被广泛使用

最终效果

输入框跳动.gif

一、添加 HTML 文件

  1. 添加一层最外层的类名为 form-control<div>
  2. form-control 里面添加一层 <input>
  3. form-control 里面添加一层 <label>
<div class="form-control">
    <input type="text" required>
    <label>Email</label>
</div>

二、添加 CSS 文件

先初始化页面

  1. 设置 *box-sizing: border-box
  2. 设置 body 来使整个项目居中
* {
    box-sizing: border-box;
}

body {
    background-color: steelblue;
    color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    overflow: hidden;
    margin: 0;
}

主要的 CSS 代码

.form-control {
    position: relative;
    margin: 20px 0 40px;
    width: 300px;
}

.form-control input {
    background-color: transparent;
    border: 0;
    border-bottom: 2px #fff solid;
    display: block;
    width: 100%;
    padding: 15px 0;
    font-size: 18px;
    color: #fff;
}

.form-control input:focus,
.form-control input:valid {
    outline: 0;
    border-bottom-color: lightblue;
}

.form-control label {
    position: absolute;
    top: 15px;
    left: 0;
    pointer-events: none;
}

.form-control label span {
    display: inline-block;
    font-size: 18px;
    min-width: 5px;
    transition: 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}

.form-control input:focus+label span,
.form-control input:valid+label span {
    color: lightblue;
    transform: translateY(-30px);
}

核心逻辑

  1. .form-control input:focus+label span.form-control input:valid+label span 添加三个属性
    • transform: translateY(-30px); 输入框获得焦点时,提示文字向上
    • color: #4158d0; 输入框获得焦点时,字体变为蓝色
  2. .form-control label 添加属性
    • pointer-events: none; 提示文字不会阻挡输入框获得焦点
  3. .form-control label span 添加属性
    • transition: 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55); 过渡动画效果

三、添加 JS 文件

主要逻辑

const labels = document.querySelectorAll('.form-control label')

labels.forEach(label => {
    label.innerHTML = label.innerText
        .split('')
        .map((letter, idx) => `<span style="transition-delay:${idx * 50}ms">${letter}</span>`)
        .join('')
})

❤️ 感谢大家

如果本文对你有帮助,就点个赞支持下吧,你的「赞」是我创作的动力。

如果你喜欢这篇文章的话,可以「点赞」 + 「收藏」 + 「转发」 给更多朋友。