我正在使用 JS 和 CSS 为表单制作动画
var userInput = document.getElementById("login-user");
var userLabel = document.getElementById("user-label");
// User Label Functions
function activeUser() {
userLabel.style.transition = "0.2s";
userLabel.style.top = "-1.5vw";
}
function deactiveUser() {
if (userInput.value.length == 0) {
userLabel.style.top = "0vw";
}
}
#login-user {
margin-bottom: 3vw;
width: 80%;
height: 3vw;
border-radius: 0.5vw;
border: solid #0057e0 0.1vw;
background: none;
color: #ddd;
text-indent: 0.5vw;
font-size: 1.5vw;
}
#user-label {
color: black;
font-size: 2vw;
position: relative;
left: 8vw;
background: #fff;
margin-right: -2vw;
font-family: 'Open Sans';
cursor: text;
transition: 0.2s;
}
<label for="login-user" onclick="activeUser()" id="user-label">Username</label>
<input type="text" name="user" id="login-user" onfocusout="deactiveUser()" onclick="activeUser()" onfocus="activeUser()">
如您所见,当我们第一次运行上面的代码段时,“用户名”文本会立即显示在上面,没有转换,但是当我们执行 onfocusout
时,它会顺利返回。想在代码执行的时候顺利到输入的最上面,但是不明白为什么不行。
答案 0 :(得分:0)
那是因为 #user-label
必须在开始时定义 top
。
刚刚在您的代码中添加了 top: 0;
,它工作正常。
var userInput = document.getElementById("login-user");
var userLabel = document.getElementById("user-label");
// User Label Functions
function activeUser() {
userLabel.style.transition = "0.2s";
userLabel.style.top = "-1.5vw";
}
function deactiveUser() {
if (userInput.value.length == 0) {
userLabel.style.top = "0vw";
}
}
#login-user {
margin-bottom: 3vw;
width: 80%;
height: 3vw;
border-radius: 0.5vw;
border: solid #0057e0 0.1vw;
background: none;
color: #ddd;
text-indent: 0.5vw;
font-size: 1.5vw;
}
#user-label {
color: black;
font-size: 2vw;
position: relative;
left: 8vw;
background: #fff;
margin-right: -2vw;
font-family: 'Open Sans';
cursor: text;
transition: 0.2s;
top: 0;
}
<label for="login-user" onclick="activeUser()" id="user-label">Username</label>
<input type="text" name="user" id="login-user" onfocusout="deactiveUser()" onclick="activeUser()" onfocus="activeUser()">