我的网站上的导航下拉菜单有一个问题,我几乎已经解决了,但还不能完全解决。我担心我可能只是把我的代码弄得一团糟。
当我引入带有 preventDefault 事件的“滚动到锚标记”功能时,它破坏了我的导航菜单。除非您再次单击菜单按钮,否则菜单不会关闭。单击其中一个链接后,我终于关闭了它,但这是现在关闭它的唯一方法。单击菜单按钮或网站上的任何其他位置时,如何关闭它?我确信那一点 jQuery 是罪魁祸首,但不知道如何修复它或解决它。
菜单的 HTML:
<div class="main-nav navbtn">
<div class="dropdown"><i onclick="myFunction()" class="dropbtn material-icons md-48"></i>
<div id="myDropdown" class="dropdown-content">
<a href="#home" class="home navlink">Home</a>
<a href="#about" class="navlink">About</a>
<a href="#services" class="navlink">Services</a>
<a href="#work" class="navlink">Work</a>
<a href="#testimonials" class="navlink">Testimonials</a>
<a href="#contact" class="navlink">Contact</a>
<a href="http://blog.ignitiondesignpdx.com" target="_blank" class="external navlink">Blog</a>
</div>
</div>
</div>
以及相关的 jQuery:
// When the user clicks on the button, toggle between hiding and showing the dropdown content
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
//// Close the dropdown menu if the user clicks outside of it
window.onclick = function (event) {
if (!event.target.matches('.dropbtn')) {
dropdowns.forEach(function (openDropdown) {
dropdown.classList.contains('show') && dropdown.classList.remove('show');
});
}
};
////This is the section I made for it to close after clicking a link
jQuery(document).ready(function ($) {
$('.dropbtn').on('click', function () {
$(".dropdown-content").show();
});
$('.navlink').on('click', function () {
$(".dropdown-content").hide();
});
});
这是搞砸其他功能的潜在问题。
//Scroll to anchor tags
$(document).on('click', 'a:not(.external)', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
var $root = $('html, body');
$('a').click(function () {
$root.animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
return false;
});
我到底应该怎么做才能修复我的菜单?
您可以在 http://idpdx.kreigd.com 上查看正在进行的网站
更新:我想我已经知道事情在哪里变得混乱了。我用来添加下拉功能的函数要求在单击 .dropbtn 元素后添加“显示”类,并在再次单击它时将其删除。
所以我真正需要做的是重新编写代码,以便单击 .dropbtn 打开下拉菜单,然后单击其他任何内容,包括导航按钮和 .dropbtn 元素,将其关闭。
更新 2:尝试不同的方法。忽略第一次更新。
Try this & let me know