当我单击<a> link?

时间:2019-03-27 19:54:24

标签: javascript jquery html css

So I am using a pure CSS nav bar that uses a checkbox to overlay a navigation menu. I am trying to get the navbar to close when I select the link. For instance, when I click the contact link it should scroll down to the id"contact" that is on the same page, however, the page scrolls down while the navbar is still showing and so I have to manually click the checkbox to close it. I have tried to solve this using some js but no luck :(

complete code link:

https://codepen.io/majorsyan/pen/Oqejox

时如何关闭导航栏
<!-- Navigation code-->
<input type="checkbox" id="nav-toggle" class="checkbox" />
<label for="nav-toggle" class="nav-toggle-btn">
<span class="nav-icon-bar"></span>
</label>
<div class="overlay"></div>
<nav class="main-nav">
<ul class="nav-list">
<li class="nav-item">
<a href="index.html" class="nav-links">Home</a>
</li>
<li class="nav-item">
<a href="portfolio.html" class="nav-links">Portfolio</a>
</li>
<li class="nav-item">
<a href="about.html" class="nav-links">About</a>
</li>
<li class="nav-item">
<a href="index.html#contact" class="nav-links">Contact</a>
</li>
</ul>
</nav>

1 个答案:

答案 0 :(得分:1)

在复选框上设置checked属性应该可以解决问题!

const links = document.querySelectorAll('.nav-item a')
const checkbox = document.querySelector('#nav-toggle')

for ( const link of links ) {
  link.onclick = handleClick
}

function handleClick() {
  checkbox.checked = false
}

或者,如果您使用的是jQuery:

$('.nav-item a').click(hideOverlay)

function hideOverlay() {
  $('#nav-toggle').prop('checked', false)
}

希望这会有所帮助! :)