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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(function() {
            $("#wrap").bind("mouseenter mouseleave", function(e) {
                var w = $(this).width();
                var h = $(this).height();
                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);






                var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4; //direction的值为“0,1,2,3”分别对应着“上,右,下,左”
                var eventType = e.type;
                var dirName = new Array('上方', '右侧', '下方', '左侧');
                if (e.type == 'mouseenter') {
                    $("#wrap").html(dirName[direction] + '进入');
                } else {
                    $('#wrap').html(dirName[direction] + '离开');
                }
            });
        });
    
    </script>

</head>
<body>
    <div id="wrap" style="width: 200px; height: 200px; border: solid 1px #000; margin-top: 100px;
        margin-left: 400px;">
    </div>
</body>
</html>

  

posted @ 2014-04-17 21:46  我是菜.鸟  阅读(174)  评论(0编辑  收藏  举报