JavaScript 动画将不起作用

JavaScript animation will not work

本文关键字:不起作用 动画 JavaScript      更新时间:2023-09-26

我正在尝试进行基本的动画测试。我复制了在此线程中作为答案提供的算法:JavaScript 动画

我复制它的尝试不起作用。我所做的只是将函数的名称更改为"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>

语法错误。试试这个:

</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/

检查引号:

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