javascript 鼠标跟随特效 <!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title></title> | |
<style> | |
*{ | |
margin: 0; | |
padding: 0; | |
} | |
body{ | |
height: 1000px; | |
} | |
div{ | |
width: 50px; | |
height: 50px; | |
background: red; | |
-webkit-border-radius: 50%; | |
-moz-border-radius: 50%; | |
border-radius: 50%; | |
text-align: center; | |
position: absolute; | |
top: 0; | |
left: 0; | |
line-height: 50px; | |
} | |
</style> | |
</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> | |
<script> | |
var oDiv=document.getElementsByTagName('div'); | |
document.onmousemove=function(e){ | |
//e等于鼠标对象 | |
e=e || window.event; | |
var maxX=window.innerWidth-oDiv[0].offsetWidth-18; | |
var maxY=window.innerHeight-oDiv[0].offsetHeight-18; //浏览器的宽度 - 第0个盒子 - 滚动条的宽度 | |
var sjyr=Math.floor(Math.random()*255); | |
var sjyg=Math.floor(Math.random()*255); | |
var sjyb=Math.floor(Math.random()*255); | |
var scrollTop=document.documentElement.scrollTop || document.body.scrollTop; | |
if(e.clientX>maxX){ | |
oDiv[0].style.left=maxX+'px'; | |
}else{ | |
oDiv[0].style.left= e.clientX+'px'; | |
} | |
if(e.clientY>maxY){ | |
oDiv[0].style.top=maxY+'px'; | |
}else{ | |
oDiv[0].style.top= e.clientY+scrollTop+'px'; | |
} | |
for(var i=oDiv.length-1;i>0;i--){ //for循环让div跟随他的上一个 | |
oDiv[i].style.left = oDiv[i-1].style.left; | |
oDiv[i].style.top = oDiv[i-1].style.top; | |
oDiv[i].style['backgroundColor'] = oDiv[i-1].style['backgroundColor']; | |
}//后者跟随前面的一个DIV | |
//滚动条滚动的距离; | |
oDiv[0].style.backgroundColor='rgb('+sjyr+","+sjyg+","+sjyb+')'; | |
/* oDiv[0].style.left= e.clientX+'px'; | |
oDiv[0].style.top= e.clientY+scrollTop+'px';*/ | |
//e.clientX 鼠标 X 距浏览器边缘多少像素 | |
//e.clientY 鼠标 Y 距浏览器边缘多少像素 | |
} | |
</script> | |
</body> | |
</html> 下面有图片: |