How do I tell if the mouse is in the DIV area

  • 2020-03-29 23:40:20
  • OfStack

Today studied this problem, also popularized the knowledge bar.

Method one:

The mouseover, mouseout event is used to determine whether the mouse is in this area. However, the limitation of this approach is that you have to trigger mouseover, or mouseout, mouseleave events to know.

function chkIn()
  div_1.innerText = " Now you've moved the mouse into the layer! "; = "normal black";
   function chkOut()
  div_1.innerText = " Now you mouse out of the layer! "; = "bold red";

<div id="div_1" style="background-color:lightblue; width:400px; height:300px; " 
       onMouseOver="chkIn()" onMouseOut="chkOut()">This is a DIV

Method 2:

function   checkIn(e){
var   x=window.event.clientX;
var   y=window.event.clientY;
var   str= ' ';
for(i=0;i <document.body.children.length;i++){
            var   obj=document.body.children[i];
          if(x> obj.offsetLeft
                                  &&x <(obj.offsetLeft+obj.clientWidth)
                          &&y> obj.offsetTop
                        &&y <(obj.offsetTop+obj.clientHeight)){
                str+= ' < Mouse on layer  ' ' The scope of > n ';
                str+= ' < Mouse on layer  ' ' Beyond the range > n ';

Method 3:

This method is the simplest and most practical.


If (mydiv.contains)

The specific situation or according to their needs to choose, I am debugging method three, but the specific also did not use. Other methods, continue to study.

Related articles: