简体   繁体   中英

There is no transition when change position of element in javascript

When I change the position left of the bg in the css there is a transition. But when i change the position in javascript there is no transition.

Steps to follow to see what im talking about

  1. in the css change the bg left from 1366px to 0. you will see a transition.

2.change the position of the bg back to 1366px.

  1. now uncomment the js code. it will change the bg position but there is no transition

here is the codepen i dont think u can change the code on stackoverflow

https://codepen.io/anon/pen/oGKMpm

 var bg = document.getElementsByClassName('bg'); // uncomment the code below. there is no transition // bg[0].style.left ='0'; 
 * { padding: 0; margin: 0; } html, body, .bg { height: 100%; width: 100%; } .bg { position: absolute; background: blue; transition: all 0.5s linear; /* change this to 0px. there will be a transition. change it back to 1366px. and then uncomment the javascript code */ left: 1366px; } 
 <div class="bg"></div> 

Its because you have used an animation property in your css styles so in order to animate using Javascript you need to define your custom animation function in JavaScript too.

(function(){
    var bg = document.getElementsByClassName('bg');
    var pos = 1366;
    setInterval(function(){ bg[0].style.left = --pos;}, 10);
})();

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