【问题标题】:jQuery + CSS: How to scroll smooth, regarding a fixed header?jQuery + CSS:如何平滑滚动,关于固定标题?
【发布时间】: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


【解决方案1】:

对于 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多