javascript动画效果之匀速运动(修订版)

时间:2023-03-09 16:42:12
javascript动画效果之匀速运动(修订版)

在编写多块同时触发运动的时候,发现一个BUG,

timer = setInterval(show, 30);本来show是一个自定义函数,
当设为timer = setInterval(show(one,two), 30);时,发现show里面的参数one和two无法被导入,所以需要做以下代码改进和优化

原版的html和css代码在这里javascript动画效果之匀速运动

js代码如下

  <script>
function $(id) {
return typeof id === "string" ? document.getElementById(id) : id;
} window.onload = function() { //定义变量
var pto = $("div");
var btn = $("show");
var timer = null;
var speed = 0; //鼠标移动绑定事件(一个无名函数)
btn.onmouseenter = function() {
//调用自定义函数,传入参数0为pto.offsetLeft需要达到的距离
showPto(0);
}
//同理
btn.onmouseleave = function() {
//同理
showPto(-200);
} //自定义函数,one为自定义参数
function showPto(one) {
//当前只需要一个定时器,所以需要在每次开始前清除定时器
clearInterval(timer);
//定义一个名为timer的定时器
timer = setInterval(function() {
if (one > pto.offsetLeft) {
//当0>pto.offsetLet时,pto需要被显示,所以speed为正值
speed = 10;
} else {
//同理,需要被隐藏时,speed为负值
speed = -10;
}
if (pto.offsetLeft == one) {
//当pto的值达到0或者-200时候就达到需求了,需要停止定时器,
clearInterval(timer);
} else {
//没有到0或者-200时候,就需要通过speed来自增或自减
pto.style.left = pto.offsetLeft + speed + 'px';
} }, 30);
}
}
</script>