<script>
var div = document.querySelector("div");
var btn = document.querySelector("button");
//动画函数封装
function fn(obj,target,callback){
//清除定时器,确保只有一个定时器工作
clearInterval(obj.timer);
//定时器设置
obj.timer = setInterval(function(){
//步长设置
// var step = (target - obj.offsetLeft) / 10;
// step > 0 ? Math.ceil(step) : Math.floor(step);
// 判断是否到达目标地点
if(obj.offsetLeft >= target){
clearInterval(obj.timer);
callback();
}
// 定位赋值
obj.style.left = obj.offsetLeft + 1 + "px";
},30)
}
// 设置点击监听事件并调用动画函数
btn.addEventListener("click",function(){
fn(div,500,function(){
div.style.backgroundColor = "red";
});
})
</script>
step变量没见题主用到?是下面的设置obj.style.left = obj.offsetLeft + step + "px";这样使用?
如果是测试也没有问题啊。最后会变红div
<div style="position:relative">DIV</div>
<button>Click Me</button>
<script>
var div = document.querySelector("div");
var btn = document.querySelector("button");
//动画函数封装
function fn(obj, target, callback) {
//清除定时器,确保只有一个定时器工作
clearInterval(obj.timer);
//定时器设置
obj.timer = setInterval(function () {
//步长设置
var step = (target - obj.offsetLeft) / 10;
console.log(step)
step > 0 ? Math.ceil(step) : Math.floor(step);
// 判断是否到达目标地点
if (obj.offsetLeft >= target) {
clearInterval(obj.timer);
callback();
}
// 定位赋值
//obj.style.left = obj.offsetLeft + 1 + "px";
obj.style.left = obj.offsetLeft + step + "px";
}, 30)
}
// 设置点击监听事件并调用动画函数
btn.addEventListener("click", function () {
fn(div, 500, function () {
div.style.backgroundColor = "red";
});
})
</script>