首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JS怎么判断鼠标进入离开的方向?

JS怎么判断鼠标进入离开的方向?

作者头像
马克社区
发布2022-07-06 20:41:29
4.5K0
发布2022-07-06 20:41:29
举报
文章被收录于专栏:高端IT高端IT
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style type="text/css">
        #box{
            width: 300px;
            height: 300px;
            margin: 80px auto 80px;
            border:1px solid red;
        }
    </style>
</head>
<body>
    <div id="box"></div>
</body>
<script type="text/javascript">
var wz = 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 );
        }
    }
    wz('box');
</script>
</html>
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647

更多内容请见原文,原文转载自:http://www.mark-to-win.com/tutorial/50910.html

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档