我是靠谱客的博主 单薄老鼠,这篇文章主要介绍js封装动画函数,现在分享给大家,希望可以做个参考。

以下俩个封装动画函数一般用于一些特效(例:轮播图,手风琴,运动的小球等等)

匀速动画函数封装

function animate(element, target) {
	//先清理定时器,这样可以保证每次点击按钮都只产生一个定时器
	clearInterval(element.timeId);
	element.timeId = setInterval(function() {
		//获取div的当前位置
		var current = element.offsetLeft;
		//设置每次移动多少像素
		var step = 10;
		step = current < target ? step : -step;
		//每次移动后的位置
		current += step;
		//判断当前位置距离目标位置多少像素
		if (Math.abs(current - target) >= Math.abs(step)) {
			element.style.left = current + "px";
		} else {
			clearInterval(element.timeId);
			element.style.left = target + "px";
		}
	}, 10);
}

变速动画函数封装

//功能函数  变速
function animate(element, target) {
	//先清理定时器,这样可以保证每次点击按钮都只产生一个定时器
	clearInterval(element.timeId);
	element.timeId = setInterval(function() {
		//获取div的当前位置
		var current = element.offsetLeft;
		//设置每次移动多少像素
		var step = (target - current) / 10;
		step = step > 0 ? Math.ceil(step) : Math.floor(step);
		//每次移动后的位置
		current += step;
		element.style.left = current + "px";
		//判断如果到达目标位置
		if (current == target) {
			//清理定时器
			clearInterval(element.timeId);
		}
	}, 10);
}


最后

以上就是单薄老鼠最近收集整理的关于js封装动画函数的全部内容,更多相关js封装动画函数内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(45)

评论列表共有 0 条评论

立即
投稿
返回
顶部