javascript 鼠標跟隨特效代碼及理解


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>


下面有圖片:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章