JavaScript如何获取鼠标移入div的方向

前几天看了百度图片带有的文字标题,它会随着鼠标的移动方向载入,觉得蛮有意思,于是就想实现这么个功能。经过一番搜索和查找,找了两种实现方法。

方法一:用四个div拼成一个区域,从哪个div移入,就是从哪个方向移入。详情参考

方法二:获取鼠标移入的那个点,距离div的左右上下哪条边最近,最近的那条边就是鼠标移入的方向。

针对方法二,自己写了个小方法,代码如下,仅供参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function getDirection(ev) {
            var mx = ev.clientX,
                    my = ev.clientY;
            var el = this.offsetLeft,
                    et = this.offsetTop,
                    ew = this.clientWidth,
                    eh = this.clientHeight;
            var left = mx - el,
                    right = el + ew - mx,
                    top = my - et,
                    bottom = et + eh - my;
            var min = Math.min.apply(Math, [left, right, top, bottom]);
            if (min === left) {
                    return "left";
            } else if (min === right) {
                    return "right";
            } else if (min === top) {
                    return "top"
            } else {
                    return "bottom";
            }
    }

本文来源:(http://www.w3cfuns.com/blog-5460967-5406975.html)

标签: js方向

评论