WCo*_*ter 5 html javascript jquery events
我有一个带有javaScript函数的网站,当用户单击导航项时,该函数应滚动到页面上的部分.在我更改导航菜单之前,此脚本有效.我无法弄清楚如何正确引用javaScript中的ID.
这是HTML导航菜单:
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Data Detective</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li><a id="home" href="#homeSect">HOME</a></li>
<li><a id="about" href="#aboutSect">ABOUT</a></li>
<li><a id="portfolio" href="#portfolioSect">PORTFOLIO</a></li>
<li><a id="contact" href="#contactSect">CONTACT</a></li>
</ul>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
这是javaScript:
$(document).ready(function() {
setBindings();
});
//Allow screen to Scroll to selected section
function setBindings() {
$("nav ul li a").click(function (tip) {
tip.preventDefault();
var sectionID = "#" + tip.currentTarget.id + "Sect";
alert('button id ' + sectionID);
$("html body").animate({
scrollTop: $(sectionID).offset().top
}, 1000);
});
}
Run Code Online (Sandbox Code Playgroud)
你应该使用.navbar类。请更换:
$("nav ul li a").click(function (tip) {
Run Code Online (Sandbox Code Playgroud)
到
$(".navbar ul li a").click(function (tip) {
Run Code Online (Sandbox Code Playgroud)
此外,我建议您使用var sectionID = $(this).attr('href');它,var sectionID = "#" + tip.currentTarget.id + "Sect";因为它更简单。