我想在onepager上使用平滑滚动。单击链接时,依赖部分应滚动到导航栏的底部。问题:导航的位置是固定的。
小提琴:http://jsfiddle.net/LNwmt/
HTML :
<nav>
<ul>
<li><a href="#section1">Section 1</a></li>
<li><a href="#section2">Section 2</a></li>
<li><a href="#section3">Section 3</a></li>
<li><a href="#section4">Section 4</a></li>
<li><a href="#section5">Section 5</a></li>
<li><a href="#section6">Section 6</a></li>
</ul>
</nav>
<section id="section1">
<h2>Section 1</h2>
<p>[...] Text [...]</p>
</section>
<section id="section2">
<h2>Section 2</h2>
<p>[...] Text [...]</p>
</section>
<section id="section3">
<h2>Section 3</h2>
<p>[...] Text [...]</p>
</section>
<section id="section4">
<h2>Section 4</h2>
<p>[...] Text [...]</p>
</section>
<section id="section5">
<h2>Section 5</h2>
<p>[...] Text [...]</p>
</section>
<section id="section6">
<h2>Section 6</h2>
<p>[...] Text [...]</p>
</section>
<footer>
Footer
</footer>
CSS :
nav {
position: fixed;
top: 0;
z-index: 3;
width: 100%;
height: 200px;
background: gray;
}
section {
border: 1px solid red;
margin: 10px 0 10px 0;
}
section:first-of-type {
margin-top: 200px;
}
footer {
height: 100px;
background: gray;
}
JS :
$(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-200 // - 200px (nav-height)
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
有谁知道,如何让这段代码正常工作?提前谢谢!
答案 0 :(得分:3)
对于Firefox,跳转滚动行为的一个修复是将位置哈希值更改为文档中不存在的哈希值。
将您的代码更改为:
$(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 - 200 // - 200px (nav-height)
}, 900, 'swing', function () {
// Replace this with something that can be easily parsed and used by your code
window.location.hash = '1' + target;
});
});
});
似乎可以解决问题:Demo jsFiddle