javascript如何判断鼠标是否在div区域内?

JavaScript一种直译式脚本语言,是一种动态类型、弱类型、基于原型的语言,内置支持类型。它的解释器被称为JavaScript引擎,为浏览器的一部分,广泛用于客户端的脚本语言,最早是在HTML(标准通用标记语言下的一个应用)网页上使用,用来给HTML网页增加动态功能。

方法一:

通过mouseover、mouseout事件,来判断鼠标是否在div区域。 但是这种方法的局限性就是,必须要触发mouseover,或mouseout,mouseleave事件才能知道。

function chkIn()
    {
  div_1.innerText = "现在你把鼠标移入层了!";
  div_1.style.font = "normal black";
 }
   function chkOut()
    {
  div_1.innerText = "现在你把鼠标移出层了!";
  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>

方法二:

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+= ' <鼠标位于层 '+obj.id+ '范围之内> \n ';
          }else{
                str+= ' <鼠标位于层 '+obj.id+ '范围之外> \n ';
        }
  }
alert(str);
}
document.onclick=checkIn

方法三:

if(myDiv.contains(window.event.srcElement))

即 if(myDiv.contains(鼠标位置的元素对象))


以上就是javascript如何判断鼠标是否在div区域内?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » JavaScript 答疑