JS實現跟隨鼠標移動的div,和一串跟隨鼠標的div,鼠標移入移出實現圖片的顏色淡入淡出
阿新 • • 發佈:2018-03-02
nload nts timer inf ntb doc tel ctype target
1.一直跟著鼠標移動的div:原理是div的left和top值有oEvent.clientX+scrollLeft鼠標指針向對於瀏覽器頁面(或客戶區)的水平坐標+元素中滾動條的水平偏移
<!DOCTYPE html> <html> <head> <title>follow mouse</title> </head> <style type="text/css"> #div1{width: 100px;height: 100px;background: red;position: absolute;} </style> <script type="text/javascript"> document.onmousemove=function(ev){ var oEvent=ev||event; var oDiv=document.getElementById(‘div1‘); var scrollTop=document.documentElement.scrollTop||document.body.scrollTop; var scrollLeft=document.documentElement.scrollLeft||document.body.scrollLeft; oDiv.style.left=oEvent.clientX+scrollLeft+‘px‘; oDiv.style.top=oEvent.clientY+scrollTop+‘px‘; } </script> <body> <div id="div1"></div> </body> </html>
2.一串跟隨鼠標移動的div們:用循環使多個div運動
yi<!DOCTYPE html> <html> <head> <title>一串跟隨鼠標的div</title> <style type="text/css"> div{width: 10px;height: 10px;background: blue;position: absolute;} </style> <script type="text/javascript"> window.onload=function(){ var aDiv=document.getElementsByTagName(‘div‘); document.onmousemove=function(ev){ var oEvent=ev||event; for(var i=aDiv.length-1;i>0;i--){ aDiv[i].style.left=aDiv[i-1].style.left; aDiv[i].style.top=aDiv[i-1].style.top; } aDiv[0].style.left=oEvent.clientX+‘px‘; aDiv[0].style.top=oEvent.clientY+‘px‘; } } </script> </head> <body> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </body> </html>
3.鼠標移入移出實現圖片的顏色淡入淡出
<!DOCTYPE html> <html> <head> <title>Fade In</title> </head> <style type="text/css"> #img1{filter:alpha(opacity:30);opacity: 0.3;} </style> <script type="text/javascript"> window.onload=function(){ var oImg=document.getElementById(‘img1‘); oImg.onmouseover=function(){ starMove(100); } oImg.onmouseout=function(){ starMove(30); } } var timer=null; var alpha=30; function starMove(iTarget){ var oImg=document.getElementById(‘img1‘); clearInterval(timer); timer=setInterval(function(){ if(alpha<iTarget){ iSpeed=10; }else{ iSpeed=-10; } if(alpha==iTarget){ clearInterval(timer); }else{ alpha+=iSpeed; oImg.style.filter=‘alpha(opacity:‘+alpha+‘)‘; oImg.style.opacity=alpha/100; } },30) } </script> <body> <img id="img1" src="images/1.jpg"> </body> </html>
JS實現跟隨鼠標移動的div,和一串跟隨鼠標的div,鼠標移入移出實現圖片的顏色淡入淡出