温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

js如何实现鼠标跟随运动效果

发布时间:2021-06-29 11:10:35 来源:亿速云 阅读:182 作者:小新 栏目:web开发

这篇文章主要介绍了js如何实现鼠标跟随运动效果,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

具体内容如下

1、使用命令创建基本结构ul.cursorPlay#cursorPlay>li*12>a>img+div>span
2、给span标签添加字段
3、设置基本的样式

  • cursorPlay的宽度 992px,高度600px

  • cursorPlay li背景为白色,内边距为8px,外边距5px,显示浮动为左浮动

  • cursorPlay li a,cursorPlay li a img显示为块状并且为相对布局

  • cursorPlay li a添加overflow:hidden

  • cursorPlay li a div为绝对布局,宽度和高度均为100%,设置背景颜色为rgba

4、js添加动态效果(方向0,1,2,3分别为上,右,下,左)

1、给绑定鼠标进入或者出去的事件

$("#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、使用getDir获取鼠标移动的方向,coordinates坐标

计算鼠标划入画出方向函数(搜索关键词“jquery计算鼠标划入划出方向”)

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、添加移动函数moveTo,三个参数分别为选择器,方向,鼠标划入画出类型,通过判断鼠标划入类型,来自定义选择器初始位置,然后重定义css样式,当鼠标划出时再重定义每个方向上的位置

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);
}

感谢你能够认真阅读完这篇文章,希望小编分享的“js如何实现鼠标跟随运动效果”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js
AI