0

I'd like to use smooth scrolling on a onepager. On clicking a link, the depending section should scroll to the nav's bottom. Problem: the nav's position is fixed.

Fiddle: 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;
    });
});
});

Does anyone know, how to make this code working fine? Thanks in advance!

4

1 回答 1

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

于 2013-09-05T17:31:17.403 回答