加咖啡喵
2017-09-29 09:22
这名话一定要加在move()函数中吗? 加与不加有什么区别吗?
window.onload = function () {
var div1 = document.getElementById('div1');
div1.onmouseover = function () {
move(0);
}
div1.onmouseout = function () {
move(-200);
}
}
var timer = null;
function move(target) {
clearInterval(timer);
timer = setInterval(function () {
var speend = 0;
if(div1.offsetLeft > target){
speend = -10;
} else {
speend = 10;
}
if(div1.offsetLeft == target){
clearInterval(timer);
} else {
div1.style.left = div1.offsetLeft + speend + 'px';
}
}, 30);
}
因为你把他写在window.onload=function里面,相当于你把
var div1 = document.getElementById('div1');
作为一个全局变量了,所以你在move里面直接是可以调用这个div1这个变量的
div1.style.left = div1.offsetLeft + speend + 'px';
至于区别 其实也没多大区别 只是你定义在window.onload里面的话在其他函数里面也可以使用
就是说如果你这个变量在不同的函数中使用次数比较多的话是可以把他直接写到window.onload里面去的,这样的话代码就不会太冗余
JS动画效果
113910 学习 · 1502 问题
相似问题