简体   繁体   中英

Why is animation (transition) not applied the first time the property is set

Here is a simple setup with a box moving using left property to the right. The property is updated by a button click. Why is transition animation not applied the first time I click on the button?

 document.addEventListener('DOMContentLoaded', () => { const box = document.querySelector('.box'); const button = document.querySelector('button'); button.addEventListener('click', () => { const current = parseInt(box.style.left); box.style.left = (isNaN(current) ? 0 : current) + 50 + "px"; }); }) 
 .box { width: 100px; height: 100px; background: green; position: relative; transition: left 1s; } 
 <button>Click me!</button> <div class="box"></div> 

The initial value of left is auto and auto is not a transitionable value.

You would need to explicitly set left: 0 to have a transition then.

Start with some initial value for left .

 document.addEventListener('DOMContentLoaded', () => { const box = document.querySelector('.box'); const button = document.querySelector('button'); button.addEventListener('click', () => { const current = parseInt(box.style.left); box.style.left = (isNaN(current) ? 0 : current) + 50 + "px"; }); }) 
 .box { left: 0; width: 100px; height: 100px; background: green; position: relative; transition: left 1s; } 
 <button>Click me!</button> <div class="box"></div> 

As "left" property is intialized as "auto", no transitions can be applied. Instead try this:

 document.addEventListener('DOMContentLoaded', () => { const box = document.querySelector('.box'); const button = document.querySelector('button'); button.addEventListener('click', () => { const current = parseInt(box.style.left); box.style.left = (isNaN(current) ? 0 : current) + 50 + "px"; }); }) 
 .box { left: 0; width: 100px; height: 100px; background: green; position: relative; transition: left 1s; } 
 <button>Click me!</button> <div class="box"></div> 

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