JavaScript animation

2020-01-26 09:48发布

I am trying to animate a div moving 200px horizontally in JavaScript.

The code below makes it jump the pixels, but is there a way to make it look animated without using jQuery?

function () {
    var div = document.getElementById('challengeOneImageJavascript');
    div.style.left = "200px";
}

7条回答
放我归山
2楼-- · 2020-01-26 10:29

You would have to use a javascript timeout function, and change the css value a little at a time. The easiest way would be to increment by a set amount each time until a threshold is reached, which would give you a linear animation, which would look clunky and amateurish compared to jQuery's default swing animation which follows a bezier curve approximately like an s-curve.

Untested code should do the linear animation

var lefty = 0;
var animate = function(){
    lefty += 20;
    var div = document.getElementById('challengeOneImageJavascript');
    div.style.left = lefty +"px";
    if(lefty < 200)
      setTimeout(animate(),100);
}

animate()

n.b. there are lots of improvements to make to that block of code, but it should get you going...

查看更多
登录 后发表回答