原生js实现鼠标跟随效果
程序员文章站
2023-11-05 18:09:40
话不多说,请看代码:
话不多说,请看代码:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>鼠标跟随效果</title> <style type="text/css"> *{margin: 0;padding: 0;} img{position:absolute;top:0;left:0;} </style> </head> <body> <img src="http://www.qdfuns.com/misc.php?mod=attach&genre=editor&aid=21984166dad229792b21c2e1277bece5" height="50" width="50" alt="" id="img"> </body> <script type="text/javascript"> (function(window){ // 获取对象 var img = document.getelementbyid("img"); // 为页面添加单击事件,鼠标点击时图片滑动到鼠标所在位置 document.onclick = function(event){ var event = event || window.event; // 获取鼠标在页面上的坐标 var pagex = event.pagex || event.clientx + document.documentelement.scrollleft; var pagey = event.pagey || event.clienty + document.documentelement.scrolltop; // 减去图片自身宽高的一半,使鼠标在图片中间 pagex = pagex - img.offsetwidth/2; pagey = pagey - img.offsetwidth/2; animate(img,{"left":pagex,"top":pagey}); }; // 封装缓动函数 function animate(obj,json,fn){ clearinterval(obj.timer); obj.timer = setinterval(function(){ var flog = true ; for( k in json ){ if( k === "zindex" ){ obj.style[k] = json[k]; }else if( k === "opacity" ){ var leader = getstyle(obj,k) * 100; var target = json[k] * 100; var step = ( target - leader ) / 10 ; step = step > 0 ? math.ceil( step ) : math.floor( step ); leader = leader + step ; obj.style[k] = leader / 100; }else{ var leader = parseint( getstyle(obj,k) ); var target = json[k]; var step = ( target - leader) / 10 ; step = step > 0 ? math.ceil( step ) : math.floor( step ); leader = leader + step; obj.style[k] = leader + "px"; }; if( leader !== target ){ flog = false; } } if( flog ){ clearinterval(obj.timer); if( fn ){ fn(); }; }; }, 15) }; // 封装获取计算后样式的函数 function getstyle(obj,attr){ if( window.getcomputedstyle ){ return window.getcomputedstyle(obj,null)[attr]; }else{ return obj.currentstyle[attr]; }; }; })(window) </script> </html>
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!