日期:2014-05-16  浏览次数:20318 次

小白问个小问题
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
div{width:30px;height:30px;background-color:#06F;position:absolute;top:0;left:0;}
</style>
<script>
function getClint(ev)
{
var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
var scrollLeft=document.documentElement.scrollLeft||document.body.scrollLeft;
return {x:ev.clientX+scrollLeft,y:ev.clientY+scrollTop}
}

document.onmousemove=function(ev)
{
var aDiv=document.getElementsByTagName("div");
var oEvent=ev||event;
var Clint=getClint(oEvent);

for(var i=aDiv.length-1;i>0;i--)
{
aDiv[i].style.left=aDiv[i-1].offsetLeft+"px";
aDiv[i].style.top=aDiv[i-1].offsetTop+"px";
}

aDiv[0].style.left=Clint.x+"px";
aDiv[0].style.top=Clint.y+"px";
}
</script>
</head>

<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>



aDiv[0~4].style.left在for中都相等了,按道理看到的是一个div随着鼠标走的,为什么是div都围着第一个走...求大神解析...
JavaScript

------解决方案--------------------
引用:
Quote: 引用:

你有5个div,你的for循环是倒的,也就是div5跟着div4,...div2跟着div1

嗯嗯,第五个跟着第四个这样下去,他们的left都是相等的了...为什么是div跟随的效果...

因为代码是写在onmousemove事件处理中。