簡體   English   中英

使用固定的頂部欄滾動到 id

[英]Scroll to id with fixed top bar

我的頁面有一個固定的頂部導航欄和頁面上的幾個 id 元素。 如果我按下這些 id 元素之一的鏈接,它會將此 id 滾動到頂部,但它隱藏在頂部導航欄下。 在野外,頁面很長並且有不同的“跳轉點”。

我有一個簡化的小提琴來顯示以下問題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解決此問題的方法。 將點擊事件綁定到頂部鏈接和底部鏈接中的<a> ,點擊事件查找目標<p>偏移並使用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/

請改用scroll-padding-top 檢查這篇文章: https://dev.to/einlinuus/fixed-navigations-and-sections-here-is-scroll-padding-25nb

修改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翻轉更容易接受,因為它們可以更容易地跟蹤頁面內容和您的確切位置。 缺點是如果有人在URL中使用#first - 他會看到菜單與標題重疊。

你可以作弊。

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM