使用requestAnimationFrame更好的实现javascript动画(转)

本文介绍了一种使用JavaScript实现元素动画的方法,通过两种不同方式来控制元素的位置变化:一种是利用定时器逐步改变元素位置;另一种是采用requestAnimationFrame进行平滑过渡。这两种方法都实现了从初始位置到目标位置的动画效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

详细说明:http://www.cnblogs.com/rubylouvre/archive/2011/08/22/2148793.html

function animate(element, name, from, to, time) {
	time = time || 800; // 默认0.8秒
	var style = element.style;

	var latency = 13; // 时间间隔 每13ms一次变化
	var count = parseInt(time / latency); // 变化的次数
	var step = Math.round((to - from) / count); // 步长 每一步的变化量
	var now = from;

	function go() {
		count--;
		now = count ? now + step : to;
		style[name] = now + 'px';
		if (count) {
			setTimeout(go, latency);
		}
	}

	style[name] = from + 'px';
	setTimeout(go, latency);
}

var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame ||
function (callback) {
	setTimeout(callback, 1000 / 60);
};

function animate1(element, name, from, to, time) {
	time = time || 800; // 默认0.8秒
	var startTime = new Date;

	function go(timestamp) {
		console.log(timestamp)

		var progress = timestamp - startTime;
		if (progress >= time) {
			element.style[name] = to + 'px';
			return;
		}

		var now = (to - from) * (progress / time);
		element.style[name] = now.toFixed() + 'px';

		//console.log(now.toFixed())
		requestAnimationFrame(go);
	}

	element.style[name] = from + 'px';

	requestAnimationFrame(go);
}

//animate1(document.getElementById('holder'), 'marginLeft', 0, 180, 500)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值