首页 > 代码库 > 跟随鼠标移动的div

跟随鼠标移动的div

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
div{
width: 10px;
height: 10px;
margin: 5px;
position: absolute;
}
</style>
<script>
function getPos(ev){
var rollTop = document.documentElement.scrollTop || document.body.scrollTop;
var rollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;

//返回一个Json
return {x: ev.clientX + rollLeft , y: ev.clientY + rollTop};
}
document.onmousemove = function(ev){
var allDiv = document.getElementsByTagName(‘div‘);
var oEvent = ev||event;
var pos = getPos(oEvent);


for(var i=allDiv.length-1;i>0;i--){
//后一个div的位置等于前一个div的位置
allDiv[i].style.left = allDiv[i-1].offsetLeft + ‘px‘;
allDiv[i].style.top = allDiv[i-1].offsetTop + ‘px‘;
}

//将第一个div左边设置为鼠标的位置
allDiv[0].style.left = pos.x + ‘px‘;
allDiv[0].style.top = pos.y + ‘px‘;
};

</script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div>L</div>
<div>o</div>
<div>v</div>
<div>e</div>
<div></div>
<div>h</div>
<div></div>
<div>u</div>
<div></div>
<div>x</div>
<div></div>
<div>i</div>
<div></div>
<div>a</div>
<div></div>
<div>o</div>
<div></div>
<div>w</div>
<div></div>
<div>e</div>
<div></div>
<div>n</div>
<div></div>
<div>h</div>
<div></div>
<div>u</div>
<div></div>
<div>x</div>
<div></div>
<div>i</div>
<div></div>
<div>a</div>
<div></div>
<div>o</div>
<div></div>
<div>w</div>
<div></div>
<div>e</div>
<div></div>
<div>n</div>
<div></div>

</body>
</html>

 

跟随鼠标移动的div