Home > Web Front-end > JS Tutorial > How to get the direction of mouse movement into div using JavaScript

How to get the direction of mouse movement into div using JavaScript

云罗郡主
Release: 2018-11-10 15:07:45
forward
1748 people have browsed it

The content of this article is about how to get the direction of moving the mouse into a div using JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

A few days ago, I saw the text captions attached to Baidu pictures. It would be loaded according to the movement direction of the mouse. I thought it was quite interesting, so I wanted to implement such a function. After some searching and searching, I found two implementation methods.

How to get the direction of mouse movement into div using JavaScript

Method 1: Use four divs to form an area. Which div you move in from is the direction you move in from.

Method 2: Get the point where the mouse moves in, which side is closest to the left, right, top, and bottom of the div. The closest side is the direction in which the mouse moves in.

For method two, I wrote a small method. The code is as follows, for reference only:

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";
            }
    }
Copy after login

The above is a complete introduction to how JavaScript gets the direction of the mouse moving into a div. If you want to know more For more information about JavaScript tutorial, please pay attention to the PHP Chinese website.


The above is the detailed content of How to get the direction of mouse movement into div using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:lvyestudy.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template