jQuery 平滑滚动锚点导航
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31832227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery smooth scrolling anchor navigation
提问by user3574766
I have a list based navigation at the top of my site, it's a one page site so the a hrefs are anchors to sections on the page. I've used this code: jQuery smooth scroll positioning doesn't work
我的网站顶部有一个基于列表的导航,它是一个单页网站,因此 a href 是页面上各部分的锚点。我用过这个代码:jQuery 平滑滚动定位不起作用
Navigation:
导航:
<nav>
<ul class="navigation">
<li class="navigation"><a class="scroll" href="#about-me">about me</a>
</li>
<li class="navigation"><a class="scroll" href="#my-skills" >my skills</a>
</li>
<li class="navigation"><a class="scroll" href="#portfolio">portfolio</a>
</li>
<li class="navigation"><a class="scroll" href="#contact">contact</a>
</li>
</ul>
</nav>
Section/div:
节/格:
<section id="contact"> <!---->
<div class="panel" id="contact">
<h2>Contact</h2>
</div>
</section> <!---->
Javascript used:
使用的Javascript:
<script type="text/javascript">
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': parseInt($target.offset().top,10);
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
</script>
The anchor works and it jumps to the section, but with no scrolling?
锚点工作并跳转到该部分,但没有滚动?
回答by Guruprasad Rao
There are few problems in your code:
你的代码有几个问题:
- You haven't closed your
li
s properly- You have same
id
s forsection
anddiv
which is invalid
- 你没有
li
正确关闭你的s- 你有相同的
id
s forsection
anddiv
which is invalid
<section id="contact"> <!---->
<div class="panel" id="contact">
So correcting the above mistakes I would like to add one more change in your JSwhich is:
因此,纠正上述错误,我想在您的JS 中再添加一项更改,即:
- No need to add
parseInt
toscrollTop
. You can directly go with theoffset().top
- 无需添加
parseInt
到scrollTop
. 你可以直接去offset().top
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top //no need of parseInt here
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
回答by user3574766
Try this code:
试试这个代码:
<script type="text/javascript">
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
var scroll;
if($(window).scrollTop()==0){
scroll = ($target.offset().top) - 160
}else{
scroll = ($target.offset().top) - 60
}
$('html, body').stop().animate({
'scrollTop': scroll
}, 900, 'swing', function () {
//window.location.hash = target;
});
});
});
</script>