监听鼠标进入、离开对象的方向

为了追求更好的用户体验,我们在添加页面效果时往往希望得知鼠标是从什么方向进入对象的,为此写了以下基于jQuery的小插件来进行监听。

 

html代码:

<div class="container"></div>

 

jQuery插件代码:

$.fn.extend({
        /**
         * 监控鼠标进入、离开对象的方向
         * @param {Function} callback : 回调(进入/离开,方向(0,1,2,3))
         */
        moveDirection:function(callback){
            var w = $(this).outerWidth(),h = $(this).outerHeight(),
                    x,y,dir;                
            $(this).bind("mouseenter",function(e){
                x = (e.pageX - $(this)[0].offsetLeft - (w / 2))*((w>h)?(h/w):1);
                y = (e.pageY - $(this)[0].offsetTop - (h / 2))*((h>w)?(w/h):1);
                dir = Math.round((Math.atan2(y,x)*(180/Math.PI)+180)/90+3)%4;
                if($.isFunction(callback)) callback("in",dir);
            });    
            $(this).bind("mouseleave",function(e){
                x = (e.pageX - $(this)[0].offsetLeft - (w / 2))*((w>h)?(h/w):1);
                y = (e.pageY - $(this)[0].offsetTop - (h / 2))*((h>w)?(w/h):1);
                dir = Math.round((Math.atan2(y,x)*(180/Math.PI)+180)/90+3)%4;
                if($.isFunction(callback)) callback("out",dir);
            });            
        }
});

 

调用方法:

$('.container').moveDirection( function(inOut,dir){
    // inOut in:进入对象, out:离开对象 
    // dir 0,1,2,3对应上右下左  
    console.log(inOut+" , "+dir); 
});

 

posted @ 2017-05-10 16:13  BarryChen89  阅读(435)  评论(0)    收藏  举报