<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{width: 100px;height: 30px;background-color: red;margin-top: 30px;}
</style>
<script>
window.onload = function(){
var DIVS = document.getElementsByTagName("div");
for(var i = 0; i < DIVS.length; i++){
DIVS[i].onmouseover = function(){
startMove(this,500);
}
DIVS[i].onmouseout = function(){
startMove(this,100);
}
}
}
function startMove(node,target){
var timer = null;
clearInterval(timer);
timer = setInterval(function(){
var speed = (target - node.offsetWidth) / 8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if(node.offsetWidth == target){
clearInterval(timer);
}else{
node.style.width = node. offsetWidth + speed + "px";
}
},30);
}
</script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
问题一:为什么把var timer = null; 放在函数内部,执行的结果就是当鼠标滑过div长度没有达到500的时候快速滑出这个时候div就会不停地闪烁快速的变长变短?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{width: 100px;height: 30px;background-color: red;margin-top: 30px;}
</style>
<script>
window.onload = function(){
var DIVS = document.getElementsByTagName("div");
for(var i = 0; i < DIVS.length; i++){
DIVS[i].onmouseover = function(){
startMove(this,500);
}
DIVS[i].onmouseout = function(){
startMove(this,100);
}
}
}
var timer = null;
function startMove(node,target){
clearInterval(timer);
var speed = (target - node.offsetWidth) / 8;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
timer = setInterval(function(){
if(node.offsetWidth == target){
clearInterval(timer);
}else{
node.style.width = node. offsetWidth + speed + "px";
}
},30);
}
</script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
为什么把speed放在
timer = setInterval(function(){
if(node.offsetWidth == target){
clearInterval(timer);
}else{
node.style.width = node. offsetWidth + speed + "px";
}
},30);
外部的时候在把鼠标放在div上再移出的时候div长度会无限加长和缩短?