JavaScript 动画 [英] JavaScript animation

查看:16
本文介绍了JavaScript 动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 JavaScript 中为 div 水平移动 200px 设置动画.

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

下面的代码使它跳跃像素,但有没有办法让它看起来动画而不使用 jQuery?

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";
}

推荐答案

这是一个基本的动画设置:

Here is a basic animation setup:

function animate(elem,style,unit,from,to,time) {
    if( !elem) return;
    var start = new Date().getTime(),
        timer = setInterval(function() {
            var step = Math.min(1,(new Date().getTime()-start)/time);
            elem.style[style] = (from+step*(to-from))+unit;
            if( step == 1) clearInterval(timer);
        },25);
    elem.style[style] = from+unit;
}

使用:

animate(
    document.getElementById('challengeOneImageJavascript'),
    "left","px",0,200,1000
);

此示例将为给定元素设置动画,使其在 1 秒(1000 毫秒)内从 0px 线性滑动到 200px.

This example will animate the given element to slide linearly from 0px to 200px over a time of 1 second (1000 ms).

这篇关于JavaScript 动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆