Home > Article > Web Front-end > How to get the direction of mouse movement into div using JavaScript
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.
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"; } }
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!