Native js realizes mouse following effect

  • 2021-07-24 09:45:19
  • OfStack

Without saying much, please look at the code:


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title> Mouse following effect </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){
 //  Get an object 
 var img = document.getElementById("img");
 //  Add a click event to the page, and the picture slides to the mouse position when the mouse clicks 
 document.onclick = function(event){
  var event = event || window.event;
  //  Gets the coordinates of the mouse on the page 
  var pageX = event.pageX || event.clientX + document.documentElement.scrollLeft;
  var pageY = event.pageY || event.clientY + document.documentElement.scrollTop;
  //  Subtracting the width and height of the picture itself 1 Half, make the mouse in the middle of the picture 
  pageX = pageX - img.offsetWidth/2;
  pageY = pageY - img.offsetWidth/2;
  animate(img,{"left":pageX,"top":pageY});
 };
 //  Encapsulated slow motion function 
 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)
 };
 //  Encapsulates the function that gets the calculated style 
 function getStyle(obj,attr){
  if( window.getComputedStyle ){
  return window.getComputedStyle(obj,null)[attr];
  }else{
  return obj.currentStyle[attr];
  };
 };
 })(window)
</script>
</html>

Related articles: