Effect:
Idea:
Use the onmousemove event to get the coordinates of the mouse, then traverse the DIVs one by one, and finally assign the coordinates of the mouse to the DIV.
Code:
Copy the code code as follows:
<head runat="server">
<title></title>
<style type="text/css">
div
{
width: 20px;
height: 20px;
background: #00FFFF;
position: absolute;
}
</style>
<script type="text/javascript">
document.onmousemove = function (ev) {
var div = document.getElementsByTagName('div');
var oEvent = ev || event; //Determine compatibility
var pos = GetMouse(oEvent); //After determining compatibility, use the function of moving the mouse coordinates to obtain the horizontal and vertical coordinates
for (var i = div.length - 1; i > 0; i--) { //Traverse DIVs, starting from the last one.
div[i].style.left = div[i - 1].offsetLeft + 'px'; //Give the previous offsetLeft to the next one
div[i].style.top = div[i - 1].offsetTop + 'px'; //Give the previous offsetTop to the next one
}
div[0].style.left = pos.x + 'px'; //Give the abscissa of the mouse to the first one
div[0].style.top = pos.y + 'px'; //Give the vertical coordinate of the mouse to the first one
}
function GetMouse(ev) { //Get the coordinates of mouse movement
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 }
}
</script>
</head>
<body>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
</body>