判断鼠标动作,可以给鼠标在标签不同区域的动作分别写不同的效果

本文介绍了一个利用JavaScript和jQuery实现的功能,能够判断鼠标在进入或离开指定元素时的方向,并据此显示不同的提示信息。此功能适用于创建交互式的弹出层等场景。

最近实现一些弹出层的页面效果,用到了需要针对鼠标从标签的不对方位进入或滑出而实现不同的效果,记录一下判断鼠标事件的demo,以便以后使用

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>判断鼠标动作,可以给鼠标在标签不同区域的动作分别写不同的效果</title>

    <script src="../js/jquery-1.9.1.min.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
   $(function(){
        $("#divmsg").bind("mouseout",
        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;
            if(direction==0)
            {
               $("#divmsg").html("上部离开");
            }
            else if(direction==1)
            {
                 $("#divmsg").html("右侧离开");
            }
            else if(direction==2)
            {
                 $("#divmsg").html("下部离开");
            }
            else if(direction==3)
            {
                 $("#divmsg").html("左侧离开");
            }
        });
         $("#divmsg").bind("mouseover",
        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;
            if(direction==0)
            {
               $("#divmsg").html("上部进入");
            }
            else if(direction==1)
            {
                 $("#divmsg").html("右侧进入");
            }
            else if(direction==2)
            {
                 $("#divmsg").html("下部进入");
            }
            else if(direction==3)
            {
                 $("#divmsg").html("左侧进入");
            }
        });
   })
    
   

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="divmsg" style="width:200px; height:200px; background-color:Gray; color:Red; text-align:center; font-size:larger; font-weight:bold; margin-left:100px;">
    判断鼠标动作
    </div>
    </form>
</body>
</html>

转载于:https://www.cnblogs.com/lanmoxiaozhu/p/3443174.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值