Math.atan2(y,x)注意:該函數的參數順序,第一個參數是y坐標,第二個參數是x坐標,這與我們平常的寫法(x, y)恰好相反。
返回值為Number類型。返回從x軸正方向通過逆時針旋轉到達坐標點(x, y)所經過的角度(單位為弧度),返回值介于 [-π, π] 之間。
atan2(x,y):返回-PI 到 PI 之間的值,是從 X 軸正向逆時針旋轉到點 (x,y) 時經過的角度。
(初步理解成從X 軸最左邊開始算角度,?逆時針旋轉經過的角度)
45°=(π/4)弧度 = 0.7853982弧度
90°= (π/2)弧度 = 1.5707964弧度(rad)
135°= (3π/4)弧度 = 2.3561946弧度(rad)180°= π弧度 = 3.1415927弧度(rad)225°= 5π/4 = 3.9269909弧度(rad)270°= 6π/4 = 4.7123891弧度(rad)315°= 7π/4 = 5.4977873弧度(rad) 360°= 2π = 6.2831855弧度(rad)
-45°= -π/4 = -0.7853982弧度(rad)-90°= -π/2 = -1.5707964弧度(rad)
原理:以div容器的中心點為圓心。對比(寬和高)的值,如取最小的高度值來作為圓的直徑畫一個圓(如圖下)。將圓劃分四個象限[?/4,3π/4),[3π/4,5π/4),[5π/4,7π/4),[-π/4,π/4);鼠標進入容器時的atan2(y,x)值分別在容器的下,右,上,左。
$("#wrap").bind("mouseenter mouseleave",function(e){
var oWidth = $(this).width();
var oheight = $(this).height();
//得到進入時的坐標角度
var posX = (e.pageX - this.offsetLeft - (oWidth/2)) * (oWidth > oheight ? (oheight/oWidth) : 1);
var posY = (e.pageY -this.offsetTop -(oheight/2))* (oheight > oWidth ? (oWidth/oheight) : 1);
//direction的值為“0,1,2,3”分別對應著“上,右,下,左”
var direction = Math.round(((Math.atan2(posY,posX) * (180/Math.PI) + 180)/90)+3)%4;
// console.log(posX);
var eventType = e.type;
var id = e.target.id;
var dirName = new Array('上方','右側','下方','左側');
var aPos = [{left:"210px",top:"-280px"},{left:"410px",top:"80px"},{left:"210px",top:"280px"},{left:"0px",top:"80px"}];
if(eventType == "mouseenter"){
// console.log(dirName[direction]+'進入');
$("#log").append(id+"觸發了onmouseenter事件");
$(".text").find("p").css(aPos[direction]).stop(true,true).animate({opacity:"1",left:"210px",top:"80px"},300)
}else{
// // console.log(dirName[direction]+'離開');
$(".text").find("p").animate(aPos[direction],300);
$("#log").append(id+"觸發了onmouseleave事件
");
}
})
//PS:如果只執行一次的話,就改成one綁定機制
代碼:var posX = (e.pageX - this.offsetLeft - (oWidth/2)) * (oWidth > oheight ? (oheight/oWidth) : 1); 計算x坐標值時,如果點原來的x坐標的絕對值大于圓的半徑值,則按 height/Width 這個比例進行縮小,使得到的點的位置在容器的邊界位置所對應的象限區間里。 y 坐標的計算也是一樣。
代碼:var direction = Math.round(((Math.atan2(posY,posX) * (180/Math.PI) + 180)/90)+3)%4;((Math.atan2(y, x) * (180 / Math.PI)將點的坐標對應的弧度值換算成角度度數值,只是為了使得到的0,1,2,3能夠與習慣性的上,右,下,左的位置對照,如果不加上180,得到的0,1,2,3就會分別對應下,右,上,左。除以90,再取四舍五入值,是一個很精妙的用法,使得可以以45°為分界線。