<!DOCTYPE html>
<html>
<head>
<title>div随鼠标移动</title>
<style type="text/css">
.ins{
background:green;
width:10px;
height:10px;
position:absolute;
border-radius:10px;
}
</style>
</head>
<body>
<div class="container"></div>
</body>
<script type="text/javascript">
function getElementByClassName(classnames){
var objArray= new Array();//定义返回对象数组
var tags=document.getElementsByTagName("*");//获取页面所有元素
var index = 0;
for(var i in tags){
if(tags[i].nodeType==1){
if(tags[i].getAttribute("class") == classnames){ //如果某元素的class值为所需要
objArray[index]=tags[i];
index++;
}
}
}
return objArray;
}
for(var i=0;i<50;i++){
var div=document.createElement("div");
div.setAttribute("class","ins");
var container=getElementByClassName("container");
container[0].append(div);
}
divs=getElementByClassName("ins");
console.log(divs.length);
document.οnmοusemοve=function(ev){
var oEvent=ev||event;
for(var i=divs.length-1;i>0;i--){
divs[i].style.left=divs[i-1].style.left;
divs[i].style.top=divs[i-1].style.top;
}
divs[0].style.left=oEvent.clientX+"px";
divs[0].style.top=oEvent.clientY+"px";
}
</script>
</html>