【问题标题】:how to move placeholder to top on focus and while typing如何在焦点和打字时将占位符移动到顶部
【发布时间】:2022-04-19 18:31:19
【问题描述】:

我正在尝试实现一个简单的输入框,当我单击该框时,占位符值会移动到顶部,但有一个问题是它总是显示在顶部。

这里是代码
https://codesandbox.io/s/magical-glitter-7ykhm?file=/src/styles.css

【问题讨论】:

  • 欢迎来到 SO,请在问题中分享您的代码,而不是在外部网站上

标签: html css reactjs


【解决方案1】:

另一种方法是创建您自己的自定义占位符(标签),这更容易使用 css 进行操作。

body {
  background: #111;
}

.input-wrap {
  position: relative;
  margin: 40px;
}

.input-wrap input {
  background: none;
  color: #c6c6c6;
  font-size: 18px;
  padding: 10px;
  display: block;
  width: 320px;
  border: none;
  border-bottom: 1px solid #ccc;
}

.input-wrap label {
  position: absolute;
  color: #c6c6c6;
  font-size: 16px;
  font-weight: normal;
  pointer-events: none;
  left: 10px;
  top: 10px;
  transition: 300ms ease all;
}

input:focus {
  outline: none;
}

.input-wrap input:focus~label,
.input-wrap input:valid ~ label{
  top: -14px;
  font-size: 12px;
  color: #328dd2;
}
<div class="input-wrap">
  <input required/>
  <label>Name</label>
</div>

【讨论】:

    【解决方案2】:

    好吧,您目前拥有的不是占位符,您的意思是做这样的事情吗?

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Static Template</title>
        <link rel="stylesheet" href="style.css" />
      </head>
      <body>
        <form>
          <input name="AnnualIncome" type="text" placeholder="Annual Income" />
          <span class="floating_label">Annual Income</span>
          <input type="submit" />
        </form>
      </body>
    </html>
    

    Code Snippet Here

    【讨论】:

    • 嗨安娜,请您将您的代码添加到您的答案中,或者最好创建一个 sn-p。如果 url 无效,这有助于保留答案。
    • 您可以使用 &lt;&gt; 按钮添加在 StackOverflow 中运行的工作示例。
    猜你喜欢
    • 1970-01-01
    • 2021-02-15
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 2015-08-15
    • 2019-05-11
    相关资源
    最近更新 更多