How does JavaScript get the direction of the mouse moving into a div? I believe that many friends who have just come into contact with JavaScript will have such questions. This chapter will introduce to you how to get the direction of the mouse moving into the 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 load 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 video tutorial, please pay attention to the PHP Chinese website.
The above is the detailed content of How does JavaScript get the direction of the mouse moving into a div? (code example). For more information, please follow other related articles on the PHP Chinese website!