js——获得鼠标滑入、滑出容器的方向

以前项目中需要有个css3动画,根据鼠标滑入、滑出容器的方向,子元素文字从滑动方向显示。以前是网上找的插件实现该效果,今天决定研究下这个单独的部分。

  • 效果
pic1.png
pic2.png
  • 代码实现
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js得到鼠标滑动方向</title>
    <script src="jquery.js"></script>
</head>
<body>
    <div id="box" style="width: 100px;height: 100px;background: #f00;margin: 100px auto;"></div>
<script>
$(function(){
    $("#box").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; 
            var eventType = e.type;
            var dirName = new Array('上方','右侧','下方','左侧'); 
            if(e.type == 'mouseenter'){
                console.log(dirName[direction]+'进入'); 
            }else{
                console.log(dirName[direction]+'离开'); 
            }
        }
    });
});
</script>
</body>
</html>

参考文章:【参考文章】

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容