js判断鼠标进入以及离开容器的方向

 

 

(注:以下代码涉及到jQuery,建议前端大牛绕路~~~)

1、遇到的问题

          如图当鼠标右箭头位置上下移动的时候  下面的城市列表容器不能隐藏。

2、方法:

    网上搜了些前端大牛们的解决办法(当然该方法不但是针对此情况的),采用判断鼠标溢出的方位来响应事件。

    具体如下:

    

 1 $(".where").bind("mouseenter mouseleave",function(e) {
 2 var w = $(this).width();
 3 var h = $(this).height();
 4 var x = (e.pageX - this.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1);
 5 var y = (e.pageY - this.offsetTop - (h / 2)) * (h > w ? (w / h) : 1);
 6 var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4; //direction的值为“0,1,2,3”分别对应着“上,右,下,左”
 7 var eventType = e.type;
 8 if(e.type == 'mouseleave'){
 9 if(direction != 2){
10 $('.citys').hide();
11 $('.where em').hide();
12 $('.where').removeClass('w-where');
13 };
14 }
15 });

代码就是这个么代码,至于原理,下面看看大牛的解释吧:

 

 源文件来自:贤心博客

posted @ 2014-11-14 16:26  lmy_moonsky  阅读(1256)  评论(0编辑  收藏  举报