Determine the direction of the mouse entering the container

<script src="jquery-3.2.1.min.js"></script>
<script> 
    $( "#div").on("mouseenter mouseleave", function (e) {
         var w = $( this ).width(); // get the box width 
        var h = $( this ).height( ); // get the box height 
        var x = (e.pageX - this .offsetLeft - (w / 2)) * (w > h ? (h / w) : 1 );
         // get the x value 
        var y = (e .pageY - this .offsetTop - (h / 2)) * (h > w ? (w / h) : 1 );
         // Get the y value 
        var direction = Math.round((((Math.atan2(y, x ) * (180 / Math.PI)) + 180) / 90) + 3) % 4; //The value of direction is "0, 1, 2, 3" corresponding to "up, right, down, left" 
        // Convert the radian value corresponding to the coordinates of the point into an angle degree value 
        var dirName = new Array('above', 'right', 'below', 'left' );
         if (e.type == 'mouseenter' ) {
            $( this ).html(dirName[direction] + 'enter' );
        } else {
            $( this ).html(dirName[direction] + 'leave' );
        }
    })

</script>

Principle code:

Draw the circle with the center point of the div container as the center of the circle and the minimum value of the height and width as the diameter. /4), [-π/4, π/4) are divided into four quadrants, and the atan2(y,x) value of the point when the mouse enters the container corresponds to the lower, right, and upper of the container border in these four quadrants. ,Left.

When calculating the x-coordinate value, if the absolute value of the original x-coordinate of the point is greater than the radius value of the circle, it will be reduced according to the ratio of h/w, so that the position of the obtained point is in the quadrant interval corresponding to the boundary position of the container. The same is true for the calculation of the y coordinate.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325165457&siteId=291194637