【发布时间】:2013-12-07 03:28:47
【问题描述】:
我想在 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;
});
});
});
有谁知道,如何使这段代码正常工作?提前致谢!
【问题讨论】:
-
这似乎可以在 Chrome 中找到 - 项目 4-6 不会一直向上滚动,因为页面长度不允许。您希望看到什么行为?
-
@dc5 你是对的,第一个项目在 Chrome 中工作,但在 Firefox 中没有。我想让它像在 Chrome 中一样工作(最重要的!),独立于浏览器。项目 4-6 的滚动也应该起作用。也许需要额外的偏移量。
-
这是触发额外滚动的哈希值。也许这篇文章会有所帮助:Modifying document.location.hash without page scrolling?
标签: javascript jquery html css scroll