我有一些 jQuery 代码,我想在这里工作。我基本上有一个垂直导航菜单,其中有两个项目,其中有弹出到侧面的 jQuery 下拉菜单。但是,当您将鼠标快速悬停在它们上方时,它们会显示为彼此重叠。所以我想要完成的是,如果一个悬停并弹出,如果另一个已经显示,它将向上滑动并隐藏。下拉式卡车已经存在,我正在添加发动机。我会继续努力,但如果有人可以提供帮助,我将不胜感激。
/* Dropdown Menu Trucks*/
$("#menu-main-menu .show-dropdown").hover(function(){
$("#dropdown").slideDown('fast');
});
$("#dropdown").mouseenter(function(){
$("#dropdown").show();
});
$("#dropdown").mouseleave(function(){
$("#dropdown").slideUp('fast');
});
// ----------------------------
/* Dropdown Menu Engines */
$("#menu-main-menu .show-dropdown2").hover(function(){
$(".dropdown-engines").slideDown('fast');
});
$(".dropdown-engines").mouseenter(function(){
$(".dropdown-engines").show();
});
$(".dropdown-engines").mouseleave(function(){
$(".dropdown-engines").slideUp('fast');
});
if ($('#dropdown').is(':visible')) {
$(".dropdown-engines").slideUp();
}
else if ($('.dropdown-engines').is(':visible')) {
$("#dropdown").slideUp();
}
编辑:让我用另一种似乎更容易完成的方式来解决这个问题..
$("#menu-main-menu .dropdown2").hover(function(){ // hover over .dropdown2
// show #dropdown-engine
$("#dropdown-engine").slideDown('fast');
});
$("#dropdown-engine").mouseenter(function(){ // mouse enter #dropdown-engine
// show #dropdown-engine
$("#dropdown-engine").show();
});
$(".dropdown2" || "#dropdown-engine").mouseleave(function(){
$("#dropdown-engine").slideUp('fast'); // mouse leave #dropdown-engine
// *or .dropdown2 slideup
}); // but only if not hovering on either
最佳答案
这个问题对我来说并不完全清楚,但我认为这是想要的。
我注意到您使用的 id 不存在于您的 jsfiddle 中,并且混合使用了类和 id。尝试保持一致并认为 DRY,通过使用数据目标和示例中的类,代码更干净、更短。
$(function(){
$(".dropdown").hide();//hide all dropdowns on start
$(".show-dropdown").mouseenter(function(){
//on mouse enter of a .show-dropdown, we slideup all .dropdowns
$(".dropdown").slideUp("fast");
//then we get the ID of the dropdown we want to show through the data-target attribute, and slide it down.
$("#"+$(this).attr("data-target")).slideDown("fast");
});
});
<ul>
<li class="show-dropdown" data-target="dropdown-trucks"><!--data target is the ID of dropdown you want to show-->
<a href="#">Trucks</a>
</li>
<li class="show-dropdown" data-target="dropdown-engines">
<a href="#">Engines</a>
</li>
</ul>
<ul id="dropdown-trucks" class="dropdown">
<li><a href="#">Truck 1</a></li>
<li><a href="#">Truck 2</a></li>
</ul>
<ul id="dropdown-engines" class="dropdown">
<li><a href="#">Detroit Series 60 Engine</a></li>
<li><a href="#">Cummins N14 Engine</a></li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于javascript - 我如何让这个 jQuery 脚本工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32895655/