js判断鼠标移动方向

js代码:

var gaga = function(wrap){
        var wrap = document.getElementById(wrap);
        var hoverDir = function(e){
            var w = wrap.offsetWidth,
                h = wrap.offsetHeight,
                x = ( e.clientX - wrap.offsetLeft - ( w / 2 ) ) * ( w > h ? ( h / w ) : 1 ),
                y = (e.clientY - wrap.offsetTop - (h / 2)) * (h > w ? (w / h) : 1),
                // 上(0) 右(1) 下(2) 左(3)
                direction = Math.round( ( ( ( Math.atan2( y, x ) * ( 180 / Math.PI ) ) + 180 ) / 90) + 3 ) % 4,
                eventType = e.type,
                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 );
        }
    }
    // gaga('gagagaga1');
    gaga('gagagaga2');


效果如下


次方法兼容所有主流浏览器,包括IE6

你可能感兴趣的:(jquery,HTML5+CSS3,js,原生js,web前端,javascript)