首页 > Web开发 > 详细

JS判断鼠标从哪个方向进入DIV容器

时间:2015-04-20 18:14:36      阅读:448      评论:0      收藏:0      [点我收藏+]
$(".flash").bind("mouseenter mouseleave",function(e){

    /** the width and height of the current div **/
    var w = $(this).width();
    var h = $(this).height();

    /** calculate the x and y to get an angle to the center of the div from that x and y. **/
    /** gets the x value relative to the center of the DIV and "normalize" it **/
    var x = (e.pageX - this.offsetLeft - (w/2)) * ( w > h ? (h/w) : 1 );
    var y = (e.pageY - this.offsetTop  - (h/2)) * ( h > w ? (w/h) : 1 );

    /** the angle and the direction from where the mouse came in/went out clockwise (TRBL=0123);**/
    /** first calculate the angle of the point, 
     add 180 deg to get rid of the negative values
     divide by 90 to get the quadrant
     add 3 and do a modulo by 4  to shift the quadrants to a proper clockwise TRBL (top/right/bottom/left) **/
    var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180 ) / 90 ) + 3 )  % 4;


    /** do your animations here **/ 
    switch(direction) {
     case 0:
     
        alert(1)
      /** animations from the TOP **/
     break;
     case 1:
        alert(2)
      /** animations from the RIGHT **/
     break;
     case 2:
        alert(3)
      /** animations from the BOTTOM **/
     break;
     case 3:
        alert(4)
      /** animations from the LEFT **/
     break;
     
}});
    

HTML:

<div class="flash">
</div>

Css:

.flash{
    width:200px;
    height:200px;
    margin-left:30%;
    background-color:red;
}

JS判断鼠标从哪个方向进入DIV容器

原文:http://www.cnblogs.com/xinlinux/p/4442175.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!