簡體   English   中英

滾動時如何將菜單置於頂部,並通過突出顯示相應的菜單鏈接來選擇適當的滾動部分

[英]How to Stick the menu at the top when scrolling and also select the appropriate scroll section by highlighting the corresponding menu link

正在嘗試在頁面滾動時以及在滾動時將菜單內容固定在頂部,應該突出顯示特定的滾動容器鏈接,並且滾動應該平滑,以支持所有設備,而不會滯后。

預期當我滾動到鏈接2數據時,如果我單擊鏈接,則鏈接2菜單選項卡也應突出顯示並也應滾動到相應部分。

這是我嘗試過的:

演示鏈接

HTML:

<div class="header_part">Header Part</div>
<div class="section_stick">
  <ul>
    <li><a href="#Link1">Link1</a></li>
    <li><a href="#Link2">Link2</a></li>
    <li><a href="#Link3">Link3</a></li>
    <li><a href="#Link4">Link4</a></li>
  </ul>
</div>
<div id="Link1">Link1 data</div>
<div id="Link2">Link2 data</div>
<div id="Link3">Link3 data</div>
<div id="Link4">Link4 data</div>

請幫助我進行更改和示例演示。

我已將您的js更新為滾動到內容部分並突出顯示滾動條上的菜單項。 您還需要稍微更改CSS。

更新了JS

var nav = $(".section_stick");
var stickyClass = "fixed_nav";
var headerHeight = $('.header_part').height();
var content = $('#Link1, #Link2, #Link3, #Link4');


$(window).scroll(function() {
    stickyMenuHandler();
    activeMenuHandler();
});


function activeMenuHandler(){
    content.each(function(){
        if(isElementInViewport($(this))){
            var _id = $(this).attr('id');
            $('.section_stick a').removeClass('is-active');
            $('.section_stick a[href="#' + _id +'"]').addClass('is-active');
        }
    });
}

function stickyMenuHandler(){
    if( $(window).scrollTop() > headerHeight ) {
        nav.addClass(stickyClass);
    } else {
        nav.removeClass(stickyClass);
    }
};

nav.find('a').click(function(e){
    e.preventDefault();
    var targetContent = $($(this).attr('href'));
    $('html, body').animate({
        scrollTop: targetContent.offset().top
    }, 500);
});

function isElementInViewport (el) {

    if (typeof jQuery === "function" && el instanceof jQuery) {
        el = el[0];
    }
    var rect = el.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
    );
}

我還更新了您的演示鏈接

暫無
暫無

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

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