单页滚动导航不适用于Javascript?



Right,所以我正在尝试使用基本的javascript创建一个简单的单页滚动导航,以便在使用函数滚动到该部分时动画化为1秒问题是它不起作用。有人有什么想法吗?

目录

<ul class="header-nav">
<li><a id="home" href="#home-View">Home</a></li>
<li><a id="about" href="#about-View">About</a></li>
<li><a href="#">Blog</a></li>
<li><a id="contact" href="#contact-View">Contact</a></li>
</ul>

爪哇语

$(document).ready(function() {
// add a click listener to each <a> tags
setBindings();
});
function setBindings() {
$(".header-nav a").click(function(e) {
// prevent anchor tags for working (?)
e.preventDefault();
var sectionID = e.currentTarget.id + "Section";
$("html body").animate({
scrollTop: $("#" + sectionID).offset().top
}, 1000)
alert("sdf");
})
}

您在标记中找不到您根据jQuery代码选择id,这就是为什么它不起作用并控制台错误,请尝试如下,

$(document).ready(function() {
// add a click listener to each <a> tags
setBindings();
});
function setBindings() {
$(".header-nav a").click(function(e) {
// prevent anchor tags for working (?)
e.preventDefault();
var sectionID = e.currentTarget.id + "-View";
console.log(sectionID);
$("html,body").animate({
scrollTop: $("#" + sectionID).offset().top
},1000);
alert("sdf");
})
}
body {
height: 1200px;
}
#home-View {
margin-top: 50px;
background: red;
height: 200px;
}
#about-View {
margin-top: 50px;
background: red;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="header-nav">
<li><a id="home" href="#home-View">Home</a></li>
<li><a id="about" href="#about-View">About</a></li>
<li><a href="#">Blog</a></li>
<li><a id="contact" href="#contact-View">Contact</a></li>
</ul>
<div id="home-View"></div>
<div id="about-View"></div>

尝试这个工作示例以导航到元素。

$(document).ready(function() {
// add a click listener to each <a> tags
setBindings();
});
function setBindings() {
$(".header-nav a").click(function(e) {

// prevent anchor tags for working (?)
e.preventDefault();
var sectionID = e.currentTarget.id + "Section";
console.log(sectionID);
$("html body").animate({
scrollTop: $("#" + sectionID).offset().top
}, 1000)
alert("sdf");
})
}
#homeSection
{
height:200px;
background-color:red;
border:1px solid #DDD;
}
#aboutSection
{
height:200px;
background-color:white;
border:1px solid #DDD;
}
#blogSection
{
height:200px;
background-color:blue;
border:1px solid #DDD;
}
#contactSection
{
height:200px;
background-color:#DDD;
border:1px solid #DDD;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="header-nav">
<li><a id="home" href="#home-View">Home</a></li>
<li><a id="about" href="#about-View">About</a></li>
<li><a id="blog" href="#">Blog</a></li>
<li><a id="contact" href="#contact-View">Contact</a></li>
</ul>


<div id="homeSection"></div>
<div id="aboutSection"></div>
<div id="blogSection"></div>
<div id="contactSection"></div>

最新更新