js 判断鼠标进去方向

function fx(id){
var  obj= document.getElementById(id);
var fun=function(e){
    var w=obj.offsetWidth;
    var h=obj.offsetHeight;
    var y=e.clientY;
    var x=e.clientX;
 var yz=(y-obj.offsetLeft-(h/2))*(h>w?(w/h):1);
 var xz=(x-obj.offsetTop-(w/2))*(w>h?(h/w):1);
 var direction = Math.round((((Math.atan2(yz, xz) * (180 / Math.PI)) + 180) / 90) + 3) % 4;
//var fangxiang=new Array("上边","右边","下边","左边");
    switch(direction){
        case 0:obj.style.background="red"
         break;
        case 1:obj.style.background="blue"
         break;
        case 2:obj.style.background="#ff0"
         break;
        case 3:obj.style.background="#2f0"
         break;        
    }
     }
    if(window.attachEvent){
    obj.attachEvent("click",fun);
    obj.attachEvent("mouseover",fun);else{obj.addEventListener("click",fun,false);
    obj.addEventListener("mouseover",fun,false);
    }
}
fx("box");

 

你可能感兴趣的:(js 判断鼠标进去方向)