欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

js实现鼠标跟随运动效果

时间:2021-02-12 08:50:14|栏目:JavaScript代码|点击:

鼠标跟随运动效果展示

1、使用命令创建基本结构ul.cursorPlay#cursorPlay>li*12>a>img+div>span

2、给span标签添加字段

3、设置基本的样式

1、cursorPlay的宽度 992px,高度600px
2、cursorPlay li背景为白色,内边距为8px,外边距5px,显示浮动为左浮动
3、cursorPlay li a,cursorPlay li a img显示为块状并且为相对布局
4、cursorPlay li a添加overflow:hidden
5、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、

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 获取元素的具体样式信息getcss(实例讲解)

栏    目:JavaScript代码

下一篇:p5.js入门教程之键盘交互

本文标题:js实现鼠标跟随运动效果

本文地址:http://www.codeinn.net/misctech/61618.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有