我有动态构建的菜单,我想在将鼠标悬停在菜单标题上时隐藏和显示该菜单。当用户没有将鼠标悬停在标题或菜单本身上时,菜单应该关闭(动画高度为 0)。
我不确定如何检查用户是否将鼠标悬停在 A 或 B 上。
这段代码在我能够使用 .hover() 时有效,但那段代码不适用于动态创建的元素,所以现在我尝试使用 .on()。
这是我的尝试:
var mychapterMenuTimer = false;
$(document).on("mouseenter", "#chapterName, .chapterMenuContainer", (function() {
//mouse enter
clearTimeout(mychapterMenuTimer);
}), function() {
//mouse leav
mychapterMenuTimer = setTimeout(function() {
$('#chapterMenu').animate({
height: '0'
}, 444);
}, 100)
});
#chapterMenu {
width: 70%;
position: absolute;
top: 40px;
height: 0px;
overflow: hidden;
}
<-- dynamically created earlier -->
<p class="chapterName">
<div id="chapterMenu" class="menuHover">
<div class="row chapterMenuContainer">
<div class="col-6 chapterList1"></div>
<div class="col-6 chapterList2"></div>
</div>
</div>
最佳答案
假设您的类和 ID 也不会动态变化,您可以使用 :hover
选择器和动画效果的 CSS 转换在 CSS 文件中实现所有这些,而无需为 javascript 绞尽脑汁逻辑。
看下面的例子;
#chapterMenu {
width: 200px;
position: absolute;
top: 80px;
height: 0px;
background-color:#ddd;
overflow: hidden;
/*animate height*/
transition: height 0.25s;
-webkit-transition: height 0.25s;
}
.chapter {
display: inline-block;
padding:10px 20px;
}
.chapter:hover #chapterMenu {
/*on chapter name hover set chapterMenu height */
height:100px;
}
<div class="chapter">
<p>Chapter 1</p>
<div id="chapterMenu" class="menuHover">
<div class="row chapterMenuContainer">
<div class="col-6 chapterList1"><a href="#">chapter1 list item 1</a></div>
<div class="col-6 chapterList2"><a href="#">chapter1 list item 2</a></div>
</div>
</div>
</div>
<div class="chapter">
<p>Chapter 2</p>
<div id="chapterMenu" class="menuHover">
<div class="row chapterMenuContainer">
<div class="col-6 chapterList1"><a href="#">chapter2 list item 1</a></div>
<div class="col-6 chapterList2"><a href="#">chapter2 list item 2</a></div>
</div>
</div>
</div>
CSS 动画的唯一缺点是旧版浏览器的支持有限。
关于jquery - 如果没有悬停在元素 A 或元素 B 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55152170/