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! ";
div_1.style.font = "normal black";
}
function chkOut()
{
div_1.innerText = " Now you mouse out of the layer! ";
div_1.style.font = "bold red";
}
<div id="div_1" style="background-color:lightblue; width:400px; height:300px; "
onMouseOver="chkIn()" onMouseOut="chkOut()">This is a DIV
</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 '+obj.id+ ' The scope of > n ';
}else{
str+= ' < Mouse on layer '+obj.id+ ' Beyond the range > n ';
}
}
alert(str);
}
document.onclick=checkIn
Method 3:
This method is the simplest and most practical.
if(myDiv.contains(window.event.srcElement))
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.