鼠标定位div实时显示

原创
小哥 3年前 (2022-11-05) 阅读数 42 #大杂烩

鼠标悬浮在div1标签上时,显示对应的div2信息层,同时鼠标在div2信息层上时,div2不隐藏。只有离开div1或者div2时,隐藏div2信息层
1、div1和div2之间不能有空隙

1、方法1(完成)



内容内容内
var btn = document.querySelector(".div1"); var box = document.querySelector(".div2"); var timer = null; box.onmouseover = btn.onmouseover = function(){ if(timer) clearTimeout(timer) box.style.display = block; } box.onmouseout = btn.onmouseout = function(){ timer = setTimeout(function(){ box.style.display = none; },400); }

2、方法2(有缺陷)

缺陷: 当div2有标签内容时,鼠标经过标签会出发隐藏事件

$(.div1).mouseover(function(){
$(.div2).show()
})

$(.div1).mouseout(function(e){ 
     var x = e.pageX;
     var y = e.pageY; 
     //x的值相对于文档的左边缘。y的值相对于文档的上边缘
     //x,y是全局变量;
     //判断鼠标是否在某DIV中
     var div = $(.div2);//获取你想要的DIV
     var y1 = div.offset().top;  //div上面两个的点的y值
     var y2 = y1 + div.height();//div下面两个点的y值
     var x1 = div.offset().left;  //div左边两个的点的x值
     var x2 = x1 + div.width();  //div右边两个点的x的值

     if( x < x1 || x > x2 || y < y1 || y > y2){
         // alert(鼠标不在该DIV中);

        $(.div2).hide()
     }else{
        $(.div2).show()
        // alert("23")
     }
});
$(.div2).mouseout(function(){
    // e.stopPropagation();
     $(.div2).hide()
})
版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除

热门