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>