简体   繁体   English

在javascript中更改元素的位置时没有过渡

[英]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. 当我更改CSS中bg的位置时,会有一个过渡。 But when i change the position in javascript there is no transition. 但是,当我更改javascript中的位置时,没有过渡。

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. 在CSS中,将左bg从1366px更改为0。您将看到一个过渡。

2.change the position of the bg back to 1366px. 2.将背景色的位置更改回1366px。

  1. now uncomment the js code. 现在取消注释js代码。 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 这是codepen,我不认为你可以在stackoverflow上更改代码

https://codepen.io/anon/pen/oGKMpm 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. 这是因为您已经在CSS样式中使用了animation属性,因此要使用Java动画制作动画,还需要在JavaScript中定义自定义动画功能。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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