A little something new every day-the mouse enters the direction of the container to judge

Source: Internet
Author: User

This thing I thought about a long time ago, how to tell which direction the mouse is entering the element? There is code and a little explanation, the usage is very subtle, write down, hope to see later can remember.

Index.html

<! DOCTYPE html>
<style>
#wrap {height:100px;width:100px;background-color: #000000;}
</style>
<script src= "Http://libs.baidu.com/jquery/1.11.1/jquery.min.js" ></script>
<body>
<div id= "Wrap" ></div>
<div id= "Result" ></div>
</body>
<script>
$ ("#wrap"). Bind ("MouseEnter mouseleave", function (e) {
var w = $ (this). width ();
var h = $ (this). Height ();
var x = (E.pagex-this.offsetleft-(W/2)) * (W > H?) (h/w): 1);
var y = (E.pagey-this.offsettop-(H/2)) * (H > w?) (w/h): 1);
var direction = Math.Round (((((Math.atan2 (y, x) * (180/MATH.PI)) + 180)/90) + 3)% 4; The value of direction "0,1,2,3" corresponds to "top, right, bottom, left" respectively.
var eventtype = E.type;
var dirName = new Array (' above ', ' right ', ' bottom ', ' left ');
if (E.type = = ' MouseEnter ') {
$ ("#result"). html (dirname[direction]+ ' enter ');
}else{
$ (' #result '). html (dirname[direction]+ ' away ');
}
});
</script>
The key thing is to understand a few parametric variables above this diagram, and the use of the atan2 () function.

Not much, what I have learned, is far more profound than the explanation, the quadrant problem in mathematics.

A little something new every day-the mouse enters the direction of the container to judge

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.