JS模拟缓冲动画时遇到的定时器问题

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>缓冲动画</title>
	<meta http-equiv="Content-Type" content="text/html;charset=gb2312" />
<style>
*{
	margin:0;
	padding:0;
}
#wrap{
	width:100px;
	height:100px;
	background:red;
	position:relative;
	left:-100px;
}
#share{
	width:20px;
	height:30px;
	background:blue;
	position:absolute;
	left:100px;
	top:35px;
	font-size:14px;
}
</style>
</head>
<body>
<div style="width:200px;height:200px;background:green;" id="btn">
<div id="wrap">
	<div id='share'>分享</div>
</div>
</div>
<script>
var wrapDiv = document.getElementById('wrap');
wrapDiv.onmouseover = function(){
	startMove(0);
};
wrapDiv.onmouseout = function(){
	startMove(-100);
};
function startMove(target){
//此处将保存定时器ID的变量在函数中进行定义,问题由此处开始
	var timer = null;//如果在全局环境中声明,则问题解除
	clearInterval(timer);//此语句没有达到预想的效果
	timer = setInterval(function(){
		var speed = (target-wrapDiv.offsetLeft)/10;
		//speed = speed>0?Math.ceil(speed):Math.floor(speed);//取消注释,修复变速运动的bug
		if(wrapDiv.offsetLeft==target){
			clearInterval(timer);
		}else{
			wrapDiv.style.left = wrapDiv.offsetLeft+speed+'px';
		}
	},50);

}
</script>
</body>
<p></html></p><p>wrapDiv的mouseover可以单独、正常触发;如果之后又触发wrapDiv的mouseout,则会造成该div在触发mouseout时产生晃动。</p><p>对于定时器的其他测试:</p><p>1.例如timer = setInterval(function(){...},time1);</p><p>timer = setInerval(function(){...},time2);</p><p>timer = ...</p><p>此处不会像我们平时声明一个变量后对其初始化,然后在对其赋其他值后销毁原来的值一样,每个定时器依然正常运行;</p><p>2.clearInterval(timer);只会取消改组定时器的最后一次设定的定时器,其他不受影响;</p><p>3.针对定时器的这一情况,建议将保存定时器调用ID的变量在全局作用域中进行声明和初始化;</p>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值