判断鼠标进入/离开某块的方向

之前看到一个挺好看的效果,就是在某块有个遮罩,随着你鼠标进入的方向遮罩进入,然后遮罩从鼠标离开的方向离开,挺好看的。
想自己写一个的时候,发现在鼠标判断这里好想并不是自己想象中那么简单。
再后来在网上看到有个大兄弟写的这个判断,哈哈,真的好,这里分享一下。

$("#wrap").bind("mouseenter mouseleave",function(e) {
           var w = $(this).width();
           var h = $(this).height();
           var x = (e.pageX - this.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1);
           var y = (e.pageY - this.offsetTop - (h / 2)) * (h > w ? (w / h) : 1);
           var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4; //direction的值为“0,1,2,3”分别对应着“上,右,下,左”
           var eventType = e.type;
           var dirName = new Array('上方','右侧','下方','左侧');
           if(e.type == 'mouseenter'){
              //在这里添加你想要的效果
              $("#result").html(dirName[direction]+'进入');
          }else{
              //同理
              $('#result').html(dirName[direction]+'离开');
          }
      });

判断鼠标进入/离开某块的方向_第1张图片

分享是一种美德。
喜欢前端,喜欢看书,喜欢运动。

你可能感兴趣的:(js知识)