一、获取鼠标坐标
clientX:鼠标到可视区边缘的距离; scrollLeft:滚动条到页面顶端的距离(不可视区的距离)
兼容性写法:
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
跟随鼠标移动的divs,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
<style>
div {
width: 10px;
height: 10px;
background: #F00;
position: absolute;
}
</style>
<script>
window.onload = function () {
document.onmousemove = function (ev) {
var oEvent = ev || event;
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
var oDivs = document.getElementsByTagName("div");
oDivs[0].style.left = oEvent.clientX + scrollLeft + "px";
oDivs[0].style.top = oEvent.clientY + scrollTop + "px";
for (var i = oDivs.length - 1; i > 0; i--) {
oDivs[i].style.left = oDivs[i - 1].style.left;
oDivs[i].style.top = oDivs[i - 1].style.top;
}
}
}
</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>
<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>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>