JavaScript鼠标跟随特效使用:
这个一个很简单的鼠标点击跟随案例,这个效果并没有大家想像的那么神奇,就两个属性;
具体代码如下:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <style>
- div {width:30px; height:30px; background:yellow;}
- #test {z-index:100; width:20px; height:20px;left:150px; top:150px; background:red; position:absolute;}
- </style>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>鼠标点击跟随的Div效果</title>
- <script>
- window.onload=function ()
- {
- document.getElementById('test').onclick=function (ev)
- {
- //console.log(ev); //查看鼠标点击的信息 (如何时点击、点击的位置等)
- var test = document.getElementById('test');
- test.style.left = ev.clientX+'px';
- test.style.top = ev.clientY+'px';
- };
- }
- </script>
- </head>
- <body>
- <div id="test"></div>
- </body>
- </html>
这是一个鼠标移动跟随特效,基本效果已经做出来,还不是很完善,有兴趣的可以继续优化下;
css样式:
- <style>
- div {width:10px; height:10px; background:red; position:absolute;}
- </style>
- <script>
- window.onload=function ()
- {
- var aDiv=document.getElementsByTagName('div');
- var i=0;
- setInterval(function(){
- for(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;
- }
- },5);
- document.onmousemove=function (ev)
- {
- var oEvent=ev||event;
- aDiv[0].style.left=oEvent.clientX+'px';
- aDiv[0].style.top=oEvent.clientY+'px';
- };
- };
- </script>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <style>
- div {width:10px; height:10px; background:red; position:absolute;}
- </style>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>跟随鼠标的Div效果</title>
- <script>
- window.onload=function ()
- {
- var aDiv=document.getElementsByTagName('div');
- var i=0;
- setInterval(function(){
- for(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;
- }
- },5);
- document.onmousemove=function (ev)
- {
- var oEvent=ev||event;
- 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>
- <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>
- <div></div>
- </body>
- </html>