js Mouse Follow Motion Effect

  • 2021-08-03 08:58:34
  • OfStack

This article example for everyone to share the js mouse following effect display of the specific code, for your reference, the specific content is as follows

1. Use the command to create the basic structure ul. cursorPlay # cursorPlay > li*12 > a > img+div > span
2. Add a field to the span tag
3. Set basic styles

The width of cursorPlay is 992px and the height is 600px The background of cursorPlay li is white, the inner margin is 8px, and the outer margin is 5px, showing that the floating is left floating cursorPlay li a, cursorPlay li a img are shown as blocks and are relatively laid out cursorPlay li a Add overflow: hidden cursorPlay li a div is an absolute layout with 100% width and height, and the background color is set to rgba

4. js adds dynamic effects (directions 0, 1, 2 and 3 are up, right, down and left respectively)

1. Events for binding mouse to enter or exit


$("#cursorPlay li").on("mouseenter mouseleave",function(event){
var evType = event.type;
var direction = getDir($(this), {
x: event.pageX,
y: event.pageY
});
//  console.log("evtype:"+evType+",dir:"+direction);
moveTo($(this),direction, evType);
});


2. Use getDir to get the direction of mouse movement and coordinates coordinates

Calculate the mouse stroke and draw direction function (search keyword "jquery Calculate the mouse stroke and draw direction")


direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4;
function getDir($el, coordinates){
var w = $el.width(),
h = $el.height(),
x = (coordinates.x - $el.offset().left - (w / 2)) * (w > h ? (h / w) : 1),
y = (coordinates.y - $el.offset().top - (h / 2)) * (h > w ? (w / h) : 1),
direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4;
return direction;
}


3. Add the moving function moveTo. The three parameters are selector, direction and mouse drawing type. By judging the mouse drawing type, the initial position of selector is customized, and then the css style is redefined. When the mouse is drawn, the position in each direction is redefined


function moveTo($el, direction, type){
  var $layer = $el.find("div");
  var coord = {};
  if(type === "mouseenter"){
    switch(direction){
     case 0 :   $layer.css("top","-100%").css("left","0px");break;
    case 1 : $layer.css("left","100%").css("top","0px");break;
    case 2 : $layer.css("top","100%").css("left","0px");break;
    case 3 : $layer.css("left","-100%").css("top","0px");break;
  }
    coord = {left:0,top:0}
  }else{
  switch(direction){
    case 0 : coord = {left:0,top:'-100%'};break;
    case 1 : coord = {left:'100%',top:0};break;
    case 2 : coord = {left:0,top:'100%'};break;
    case 3 : coord = {left:'-100%',top:0};break;
  }
}
$layer.animate(coord,300);
} 

Related articles: