简体   繁体   中英

Animation transition not running at first click

I am doing an animation for a form with JS and 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()">

As you can see, when we first run the snippet above, the "username" text just goes above instantlly, without the transition, but when we do the onfocusout , it returns smoothly. I want to go smoothly to the top of the input when the code is executed, but I don't understand why it isn't.

That's because #user-label has to top defined in the beginning. Just added top: 0; to your code and it works fine.

 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()">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM