我正在尝试让我的代码滚动,以便当用户点击导航链接时,它会特别滚动到该部分。我无法弄清楚哪一行代码是错误的,因为当我点击它时,它会带我进入它不会滚动的部分。
$('.scroll-to').on('click', function(e) {
e.preventDefault();
var thisTarget = $(this).attr('href');
var targetOffset = $(thisTarget).offset().top;
$('html, body').animate({
scrollTop: targetOffset
}, 600);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="navigation">
<section>
<div class="navlinks">
<a href="#about" class="scroll-to">about</a>
<a href="3skills" class="scroll-to">skills</a>
<a href="#work" class="scroll-to">work</a>
<a href="#youtube" class="scroll-to">youtube</a>
<a href="#recommendation" class="scroll-to">recommendations</a>
<a href="#contactform" class="scroll-to">contact</a>
</div>
</section>
</nav>
&#13;
答案 0 :(得分:0)
您的上述代码按预期工作;只有两件事可能是错的:
ID
元素
另请注意,元素不能以ID开头,因此您的3skills
元素永远无法滚动。我假设这只是哈希的拼写错误,因此我将其更改为#skills
。
添加链接并确保它们不以数字开头会产生一个工作示例,如下所示:
$('.scroll-to').on('click', function(e) {
e.preventDefault();
var thisTarget = $(this).attr('href');
var targetOffset = $(thisTarget).offset().top;
$('html, body').animate({
scrollTop: targetOffset
}, 600);
});
#about {
margin-top: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navlinks">
<a href="#about" class="scroll-to">about</a>
<a href="#skills" class="scroll-to">skills</a>
<a href="#work" class="scroll-to">work</a>
<a href="#youtube" class="scroll-to">youtube</a>
<a href="#recommendation" class="scroll-to">recommendations</a>
<a href="#contactform" class="scroll-to">contact</a>
</div>
<div id="about">Lorem ipsum</div>
<div id="skills">Lorem ipsum</div>
<div id="work">Lorem ipsum</div>
<div id="youtube">Lorem ipsum</div>
<div id="recommendation">Lorem ipsum</div>
<div id="contactform">Lorem ipsum</div>
希望这有帮助!