How change css using variables to make an animation

半世苍凉 提交于 2019-12-08 04:11:14

问题


How can I transition CSS values using JavaScript? I made this code, but it isn't working:

var num = 100;
function fillDiv{
var a=document.getElementById("principal");
for (var i = 0; i<100; i++){
    num=num-25;
    a.style.background="-moz-radial-gradient(#FFFFFF "+num+"%, #006699 200%);";
    if (num==0){
       break;
    }
 }

In the debug window all gone good, but when I check it on elements tag the value hasn't changed.


回答1:


As explained in comments, the for loop is too quick to notice the effect, Instead you may use interval, set the interval period to 40 this is like 25 frames per second, also made the step 10 instead of 4 in num = num - 10; so that the animation will look smooth and noticeable like below:

JS Fiddle

var num = 100;

var $interval = setInterval(function() {
  var a = document.getElementById("principal");
  num = num - 10;
  if (num >= 0) {
    a.style.background = '-moz-radial-gradient(#FFF ' + num + '%,#1e69de 200%)';
    a.style.background = '-webkit-radial-gradient(#FFF ' + num + '%,#1e69de 200%)';
    a.style.background = 'radial-gradient(#FFF ' + num + '%,#1e69de 200%)';
  } else {
    clearInterval($interval);
  }
}, 40);
body {
  margin: 0;
  padding: 0;
}
#principal {
  width: 100vw;
  height: 100vh;
  display: block;
  background-color: #1e69de;
  margin: 0 auto;
}
<div id="principal"></div>


来源:https://stackoverflow.com/questions/33892656/how-change-css-using-variables-to-make-an-animation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!