如何使用jQuery实现鼠标悬停时已显示的div保持不隐藏
问题原因
现有代码仅监听了#box1的悬停事件,鼠标移出#box1时就会直接触发#box2的淡出逻辑,无论鼠标是否移动到相邻的#box2上,因此会出现鼠标移入#box2时元素直接消失的问题。
实现方案
两种方案可按需选择:
方案1:不改动现有HTML/CSS结构,仅修改JS逻辑
通过增加延时判断,预留鼠标从#box1移动到#box2的缓冲时间,同时避免动画叠加:
let hideTimer = null; // 给两个元素同时绑定鼠标进出事件 $("#box1, #box2").on("mouseenter", function() { clearTimeout(hideTimer); // stop方法用于清空之前未执行完的动画,避免动画堆积 $("#box2").stop(true, true).fadeIn("slow"); }).on("mouseleave", function() { hideTimer = setTimeout(() => { $("#box2").stop(true, true).fadeOut(); // 200ms为缓冲时间,可根据实际需求调整 }, 200); });
方案2:少量修改HTML/CSS,逻辑更简洁
将两个元素放在同一个父容器内,直接给父容器绑定悬停事件,只要鼠标还在父容器范围内就不会触发隐藏:
调整后HTML
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <!-- 新增父容器 --> <div class="box-wrapper"> <div class="box1" id="box1"></div> <div class="box2" id="box2"></div> </div>
调整后CSS
/* 父容器定位覆盖两个子元素的范围 */ .box-wrapper { position: absolute; left: 4%; width: 40%; height: 30%; } .box1 { position: absolute; left: 0; width: 50%; height: 33%; background-color: black; } .box2 { position: absolute; left: 50%; width: 50%; height: 100%; background-color: grey; display:none; }
调整后JS
$(".box-wrapper").hover(function(){ $("#box2").stop(true, true).fadeIn("slow"); }, function(){ $("#box2").stop(true, true).fadeOut(); });
内容的提问来源于stack exchange,提问作者seriously
相关产品推荐
相关产品推荐

