【问题标题】:Scroll to id with fixed top bar使用固定顶栏滚动到 id
【发布时间】:2013-02-14 21:16:32
【问题描述】:

我的页面有一个固定的顶部导航栏,页面上有几个 id 元素。如果我按下这些 id 元素之一的链接,它会将这个 id 滚动到顶部,但它隐藏在顶部导航栏下。在野外,页面很长,并且有不同的“跳转点”。

我有a simplified fiddle to show the problem 带有以下html

<div id="fixedbar">This is the fixed top bar</div>
<div id="toplinks"><a href="#first">First</a> <a href="#second">Second</a></div>
<p id="first"><strong>First</strong>
    Lorem ipsum dolor sit amet[...]
</p>
<p id="second"><strong>Second</strong>
    Duis autem vel eum iriure dolor[...]
</p>
<div id="bottomlinks"><a href="#first">First</a> <a href="#second">Second</a></div>

还有这个css

body{padding:0;margin:0}
#toplinks{padding-top:2em}
#fixedbar{
    position:fixed;
    background-color:#ccc;
    height:2em;
    width:100%
}

我希望点击链接滚动到正确的元素,但补充固定的导航栏。 一个可能的解决方案最好只包含 css,但可以包含 javascript 或 jquery(1.9 用于生产)。

感谢您的帮助!

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    你可以作弊一点。

    http://jsfiddle.net/vyPkA/

    body{padding:0;margin:0}
    #toplinks{padding-top:2em; margin-bottom: -40px;}
    #fixedbar{
        position:fixed;
        background-color:#ccc;
        height:2em;
        width:100%;
    }
    #first, #second{
        padding-top: 40px;
    }
    

    【讨论】:

    • 填充会破坏页面上其他元素的布局。所以这行不通:(
    【解决方案2】:

    修改后的JS:

     $("#toplinks a").click(function() {
        var id =  $(this).attr('href');
         $('html, body').animate({         
             scrollTop: $(id).offset().top-40
         }, 1000);
     });
    

    修改后的 CSS:

    body{padding:0;margin:0}
    #toplinks{padding-top:2em}
    #fixedbar{
        position:fixed;
        background-color:#ccc;
        height:40px;
        width:100%
    }
    

    小提琴:http://jsfiddle.net/xSdKr/

    40(px) 是菜单高度,1000 是执行动画的时间(以毫秒为单位)。

    JS 解决方案比纯 CSS 优雅得多,主要是因为它可以将元素保留在适当的位置,而没有任何可能会干扰您的网站样式的人工填充。它还包括动画——人们通常会发现平滑过渡比使用纯 CSS/HTML 的 insta-flips 更容易接受,因为它们更容易跟踪页面内容和您的确切位置。缺点是如果有人在 URL 中使用 #first - 他会看到菜单与标题重叠。

    【讨论】:

    • 感谢您的建议,我尝试并修改了,但 Dereks 的回答完成了这项工作。
    【解决方案3】:

    这是解决此问题的 JavaScript 解决方案。在toplinks和bottomlinks中绑定一个点击事件到&lt;a&gt;,在点击事件上找到目标&lt;p&gt;的偏移量并使用javascript滚动到它。

    $("#toplinks, #bottomlinks").on('click','a', function(event){ 
        event.preventDefault();
        var o =  $( $(this).attr("href") ).offset();   
        var sT = o.top - $("#fixedbar").outerHeight(true); // get the fixedbar height
        // compute the correct offset and scroll to it.
        window.scrollTo(0,sT);
    });
    

    小提琴:http://jsfiddle.net/AnmJY/1/

    【讨论】:

    • +1 用于计算固定条高度,而不是使用近似值/猜测。我为完整性添加了一些调整 =)
    • 感谢这就像一个魅力。我把头像改成$('a[href^="#"]').on('click keyup',,但你的回答对我来说是缺失的提示。
    • 感谢您调整我的代码,Raad。不客气,Bastian Rang =]
    猜你喜欢
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多