您的位置:首页 > 其它

关于直接声明变量时直接初始化为setInterval

2016-08-20 15:46 106 查看
<script type="text/javascript">
window.onload=function(){
var move=document.getElementById("move");
move.onmouseover=function(){
moveStart(0);
}
move.onmouseout=function(){
moveStart(-200);
}
}
function moveStart(target){
clearInterval(doMove);
var speed=0;
if (move.offsetLeft<target){
speed=10;
}else{
speed=-10;
}
var doMove=setInterval(function(){

if (move.offsetLeft==target){
clearInterval(doMove);
}else {
move.style.left=move.offsetLeft+speed+"px";
console.log(move.offsetLeft);
}
},30);
}
</script>


看完教程后自己敲的代码,结果发现实现的效果为持续性的出出入入,div的left属性一直保持在0和-10不断变换。

最后在贴吧找到了原因

var doMove=setInterval(function(){

if (move.offsetLeft==target){
clearInterval(doMove);
}else {
move.style.left=move.offsetLeft+speed+"px";
console.log(move.offsetLeft);
}
},30);


关于这部分,每次执行 move的时候,都会重新声明一个未设置的局部 doMove。

由於是局部变量,所以只限於本次的 move可使用。下一次的 move会有新的 doMove,与上次无关。

下面就是修改后的代码,声明全局变量var doMove=null,这样在setInterval 跟 clearInterval 读取的是同一个 doMove

<script type="text/javascript">
window.onload=function(){
var move=document.getElementById("move");
move.onmouseover=function(){
moveStart(0);
}
move.onmouseout=function(){
moveStart(-200);
}
}
var doMove=null;
function moveStart(target){
clearInterval(doMove);
var speed=0;
if (move.offsetLeft<target){
speed=10;
}else{
speed=-10;
}
doMove=setInterval(function(){

if (move.offsetLeft==target){
clearInterval(doMove);
}else {
move.style.left=move.offsetLeft+speed+"px";
console.log(move.offsetLeft);
}
},30);
}
</script>


参考的帖子:http://tieba.baidu.com/p/3357702662#
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: