偶然將想到的一個如何判斷滑鼠從哪個方向進入一個容器的問題。首先想到的是給容器的四個邊添加幾個塊,然後看滑鼠進入的時候哪個塊先監聽到滑鼠事件。不過這樣麻煩太多了。google了一下找到了一個不錯的解決方案,是基於jquery的,原文地址
說實話,其中的var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4;這句用到的數學知識我是真沒有看明白,原文中有一些英文注釋我就不一一說明了。代碼部分不是很多,我直接寫了個樣本。
</p><p><!DOCTYPE html><br /><html><br /><head><br /><meta charset="UTF-8"><br /><title>判斷滑鼠進入方向</title><br /></head><br /><body><br /><style><br />html,body{margin:0;padding:0;}<br />#wrap{width:300px;height:300px;background:#33aa00;margin:50px;display:inline-block;font-size:50px;text-align:center;line-height:300px;}<br /></style><br /><div id="wrap"><br /> 方向反饋<br /></div><br /><script type="text/javascript" src="http://common.cnblogs.com/script/jquery.js"></script><br /><script><br />$("#wrap").bind("mouseenter mouseleave",<br />function(e) {<br />var w = $(this).width();<br />var h = $(this).height();<br />var x = (e.pageX - this.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1);<br />var y = (e.pageY - this.offsetTop - (h / 2)) * (h > w ? (w / h) : 1);<br />var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4;<br />var eventType = e.type;<br />var dirName = new Array('上方','右側','下方','左側');<br />if(e.type == 'mouseenter'){<br />$(this).html(dirName[direction]+'進入');<br />}else{<br />$(this).html(dirName[direction]+'離開');<br />}<br />});<br /></script><br /></body><br /></html><br />
運行代碼
滑鼠移動到上面,可以看到效果。其中返回的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/