gpt4 book ai didi

javascript - Jquery slideup slidedown 意外行为

转载 作者:行者123 更新时间:2023-11-30 12:27:12 24 4
gpt4 key购买 nike

我发现了很多类似的问题,但找不到可以解决我问题的答案。

我有一个 ID 为“first”的 div。我想要的只是当鼠标位于第一个 div 上时向下滑动另一个 ID 为 'second' 的 div,当鼠标不在该 div 上时 slideup div 'second'。

下面的代码运行良好,但存在一些问题。

1) 当鼠标在 - 它滑动两次。

2) 当第二个 div 关闭并且我将鼠标移到 div 上时,它再次滑动

你能帮我得到我想要的结果吗。

html

<div>
<div id="zero"><div>
<div id="my_hover">
<div id="second"></div>
<div id="first"></div>
</div>
<div id="third"></div>
</div>

js

$(document).ready(function(){
$("#first").mouseenter(function(){
$("#second").stop().slideDown("slow");
});
$("#first").mouseout(function(){
$("#second").slideUp("slow");
});
});

最佳答案

最简单的方法是将 pointer-events: none; 添加到 #second div CSS 并将其定位在 #first div 之上.

pointer-events: none; In addition to indicating that the element is not the target of mouse events, the value none instructs the mouse event to go "through" the element and target whatever is "underneath" that element instead.
(...)
The element is never the target of mouse events; however, mouse events may target its descendant elements if those descendants have pointer-events set to some other value. In these circumstances, mouse events will trigger event listeners on this parent element as appropriate on their way to/from the descendant during the event capture/bubble phases.

Reference

$(document).ready(function(){
var slide = $("#second");
$("#first").hover(function(){
slide.stop().slideDown("slow");
},function(){
slide.slideUp("slow");
});
});
#first { 
width: 100px;
height: 100px;
background:red;
}

#second {
position: absolute;
display: none;
width: 100px;
height: 100px;
background:blue;
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="second">Second</div>
<div id="first">First</div>


另一种方法是将这两个元素插入到另一个元素中,并为该元素使用 hover 而不是 div #first。这样,整个区域都是敏感的:

$(document).ready(function(){
var slide = $("#second");
$(".my-hover").hover(function(){
slide.stop().slideDown("slow");
},function(){
slide.slideUp("slow");
});

//for demo:
$('.btn').click(function(){
alert('it works!');
});

});
#first { 
width: 100px;
height: 100px;
background:red;
}

#second {
position: absolute;
display: none;
width: 100px;
height: 100px;
background:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=my-hover>
<div id="second"><button class=btn>BUTTON</button></div>
<div id="first">First</div>
</div>

关于javascript - Jquery slideup slidedown 意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28967990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com