JS实现跟随鼠标移动的div,和一串跟随鼠标的div,鼠标移入移出实现图片的颜色淡入淡出
Posted 筱风能动浪,岸树不遮山
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS实现跟随鼠标移动的div,和一串跟随鼠标的div,鼠标移入移出实现图片的颜色淡入淡出相关的知识,希望对你有一定的参考价值。
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,鼠标移入移出实现图片的颜色淡入淡出的主要内容,如果未能解决你的问题,请参考以下文章
用js控制div跟随鼠标移动,鼠标点击后,鼠标离开,div留在当前点击的位置怎么做