美文网首页前端学习Web前端之路程序员
js——获得鼠标滑入、滑出容器的方向

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

作者: webCoder | 来源:发表于2016-04-01 16:15 被阅读844次

以前项目中需要有个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>

参考文章:【参考文章】

相关文章

网友评论

    本文标题:js——获得鼠标滑入、滑出容器的方向

    本文链接:https://www.haomeiwen.com/subject/gxsylttx.html