0, 7, 14, 21 .... 280, 287, 294, 301, ... 490, 497, 504. 从497变成504跳过了500px,所以div停不下来,那怎么办呢?修改下判断条件就可以了.
oBtn.onclick = function () {
timer = setInterval( function(){
if ( oBox.offsetLeft >= 500 ) {
oBox.style.left = 500 + 'px';
clearInterval( timer );
}else {
oBox.style.left = oBox.offsetLeft + 7 + 'px';
}
}, 1000 / 16 );
}
把条件变成>=500 清除定时器, 同时还要加上这句代码oBox.style.left = 500 + 'px',让他强制被停在500px, 否则div就不会停在500px, 而是504px了,还有一个问题,如果在div运动的过程中,你不停的点击按钮,会发现, div开始加速运动了,而不是每次加10px了,这又是为什么呢?这是因为,每次点击一下按钮,就开了一个定时器,每次点击一个按钮就开了一个定时器,这样就会有多个定时器叠加,那么速度也会产生叠加,所以div开始加速了,那么我们要让他保持10px的速度,意思就是不要让定时器叠加,更通俗点说就是确保一个定时器在开着。应该怎么做呢?
oBtn.onclick = function () {
clearInterval( timer );
timer = setInterval( function(){
if ( oBox.offsetLeft >= 500 ) {
oBox.style.left = 500 + 'px';
clearInterval( timer );
}else {
oBox.style.left = oBox.offsetLeft + 7 + 'px';
}
}, 1000 / 16 );
}
只需要在每次点击按钮的时候,清除之前的定时器就可以了,这样就能确保始终一个定时器开着,至此,一个最基本的匀速运动结构就完成了,那么我们可以把他封装成函数
function animate(obj, target, speed) {
clearInterval(timer);
timer = setInterval(function () {
if (obj.offsetLeft == target) {
clearInterval(timer);
} else {
obj.style.left = obj.offsetLeft + speed + 'px';
}
}, 30);
}
有了这个函数之后,我们来小小的应用一下。
http://www.jiathis.com/getcode
打开这个网站,你注意看他右边有个侧栏式效果(分享到),这种特效在网站上很普遍

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>侧边栏 - by ghostwu</title>
<style>
#box {
width: 150px;
height: 300px;
background: red;
position: absolute;
left: -150px;
top: 50px;
}
#box div {
width: 28px;
height: 100px;
position: absolute;
right: -28px;
top: 100px;
background: green;
}
</style>
<script>
window.onload = function () {
var timer = null;
var oBox = document.getElementById("box");
oBox.onmouseover = function () {
animate(this, 0, 10);
}
oBox.onmouseout = function () {
animate(this, -150, -10);
}
function animate(obj, target, speed) {
clearInterval(timer);
timer = setInterval(function () {
if (obj.offsetLeft == target) {
clearInterval(timer);
} else {
obj.style.left = obj.offsetLeft + speed + 'px';
}
}, 30);
}
}
</script>
</head>
<body>
<div id="box">
<div>分享到</div>
</div>
</body>
</html>
内容版权声明:除非注明,否则皆为本站原创文章。
