Clear float
window.onload=function(){
var op=document.getElementById("p1");
op.onmouseover=function(){
startMove(1);
}
op.onmouseout=function(){
startMove(0);
}
//op.onmouseover=startMove(1);
//op.onmouseout=startMove(0);
}
var timer=null;
function startMove(x){
clearInterval(timer);
var p1=document.getElementById("p1");
timer=setInterval(function(){
if(x==1&&p1.offsetLeft<0){
p1.style.left=p1.offsetLeft+10+'px';
}
else if(x==0&&p1.offsetLeft>-200){
p1.style.left=p1.offsetLeft-10+'px';
}
},30)
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
op.onmouseover 的值是处理 onmouseover 事件的事件处理函数。
而
startMove(1),因为函数名后面加了(),所以函数立即执行了,并且执行结果的返回值是 undefined。所以op.onmouseover = startMove(1)就等同于op.onmouseover = undefined。所以无效。注释的代码,绑定上去的是startMove()方式的返回值;看下下面的代码,同样的道理;
op.onmouseover=startMove(1);
op.onmouseout=startMove(0);
**1、startMove(1)、startMove(0) 这两个函数的返回值均为 undefined
2、javascript没有重载,在相同的作用域里,后面的startMove(0)、会覆盖前面的startMove(1)**
绑定匿名函数:
绑定外部通用函数,
楼主注释的写法,相当于执行函数
下面这种相当于动态调用函数(有点eval的意思),因此不会传入event对象,同时,如果用this指向的是window,不再是触发事件的dom对象。