动画过渡在第一次点击时没有运行



我正在用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()">

可以看到,当我们第一次运行上面的代码片段时,"username"文本只是立即在上面,没有过渡,但是当我们做onfocusout时,它会平滑地返回。我想在执行代码时流畅地跳转到输入的顶部,但我不明白为什么不行。

这是因为#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()">

最新更新