JS判断鼠标从什么方向进入一个容器

2012-11-07 00:12

JS判断鼠标从什么方向进入一个容器

by 司徒正美

at 2012-11-06 16:12:00

original http://www.cnblogs.com/rubylouvre/archive/2012/11/06/2757175.html

偶然将想到的一个如何判断鼠标从哪个方向进入一个容器的问题。首先想到的是给容器的四个边添加几个块,然后看鼠标进入的时候哪个块先监听到鼠标事件。不过这样麻烦太多了。google了一下找到了一个不错的解决方法,是基于jquery的,原文地址

说实话,其中的var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4;这句用到的数学知识我是真没有看明白,原文中有一些英文注释我就不一一说明了。代码部分不是很多,我直接写了个示例。

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>判断鼠标进入方向</title></head><body><style>html,body{margin:0;padding:0;}#wrap{width:300px;height:300px;background:#33aa00;margin:50px;display:inline-block;font-size:50px;text-align:center;line-height:300px;}</style><div id="wrap"> 方向反馈</div><script type="text/javascript" src="http://common.cnblogs.com/script/jquery.js"></script><script>$("#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;var eventType = e.type;var dirName = new Array('上方','右侧','下方','左侧');if(e.type == 'mouseenter'){$(this).html(dirName[direction]+'进入');}else{$(this).html(dirName[direction]+'离开');}});</script></body></html>

运行代码

鼠标移动到上面,可以看到效果。其中返回的direction的值为“0,1,2,3”分别对应着“上,右,下,左”
所以结果值可以switch循环




switch (direction) {
case 0:
$(this).html('上方进入');
break;
case 1:
$(this).html('右侧进入');
break;
case 2:
$(this).html('下方进入');
break;
case 3:
$(this).html('左侧进入');
break;
}

原文代码是基于jquery的,后面我写了个原生的js效果,代码没有封装,给需要的朋友。由于firefox等浏览器不支持mouseenter,mouseleave事件,所以我暂时用mouseover,mouseout代替了,如果大家需要解决冒泡问题的话,还是自行搜索兼容性解决方法吧。



var wrap = document.getElementById('wrap');
var hoverDir = function(e){
var w=wrap.offsetWidth;
var h=wrap.offsetHeight;
var x=(e.clientX - wrap.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1);
var y=(e.clientY - wrap.offsetTop - (h / 2)) * (h > w ? (w / h) : 1);
var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4;
var eventType = e.type;
var dirName = new Array('上方','右侧','下方','左侧');
if(e.type == 'mouseover' || e.type == 'mouseenter'){
wrap.innerHTML=dirName[direction]+'进入';
}else{
wrap.innerHTML=dirName[direction]+'离开';
}
}
if(window.addEventListener){
wrap.addEventListener('mouseover',hoverDir,false);
wrap.addEventListener('mouseout',hoverDir,false);
}else if(window.attachEvent){
wrap.attachEvent('onmouseenter',hoverDir);
wrap.attachEvent('onmouseleave',hoverDir);
}

作者:痞子

原贴地址:http://www.niumowang.org/javascript/js-direction/

本文链接