JavaScript动画无效

时间:2015-01-28 12:17:15

标签: javascript animation

我正在尝试进行基本的动画测试工作。我在这个帖子中复制了作为答案提供的算法:JavaScript animation

我尝试复制它是不行的。我所做的只是将函数的名称更改为" anim"并且可能改变了调用函数的方法。我究竟做错了什么?     

#test {
position: absolute;
left: 140px;
}

</style>
<body onload="anim(document.getElementById("test"), "left", "px", 140, 300, 500);>
 <p id="test">LOL</p>


<script>
function anim(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;
}
</script>
</body>

2 个答案:

答案 0 :(得分:0)

语法错误。试试这个:

</style>
<body onload="anim(document.getElementById('test'), 'left', 'px', 140, 300, 500);">
<p id='test'>LOL</p>


<script>
function anim(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;
}
</script>
</body>

并且jsFiddle:http://jsfiddle.net/rwowf5j8/

答案 1 :(得分:0)

检查引号:

onload="anim(document.getElementById('test'), 'left', 'px', 140, 300, 500);">