【发布时间】:2022-04-19 18:31:19
【问题描述】:
我正在尝试实现一个简单的输入框,当我单击该框时,占位符值会移动到顶部,但有一个问题是它总是显示在顶部。
这里是代码
https://codesandbox.io/s/magical-glitter-7ykhm?file=/src/styles.css
【问题讨论】:
-
欢迎来到 SO,请在问题中分享您的代码,而不是在外部网站上
我正在尝试实现一个简单的输入框,当我单击该框时,占位符值会移动到顶部,但有一个问题是它总是显示在顶部。
这里是代码
https://codesandbox.io/s/magical-glitter-7ykhm?file=/src/styles.css
【问题讨论】:
另一种方法是创建您自己的自定义占位符(标签),这更容易使用 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>
【讨论】:
好吧,您目前拥有的不是占位符,您的意思是做这样的事情吗?
<!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>
【讨论】:
<> 按钮添加在 StackOverflow 中运行的工作示例。