简体   繁体   中英

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

Was giving a try to fix the menu content to the top when the page scrolls and also when scrolling the particular scroll container link should get highlighted and the scrolling should be smooth which supports all the devices, without lagging.

Expected When I scroll to Link 2 data then the Link 2 menu tab should highlited ans also if i click on the link then also it should scroll to corresponding section.

Here it is what I tried:

demo Link

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>

Please help me out with the changes and a sample demo.

I have updated your js for scroll to the content section & highlight menu item on scroll. You also need to change your css a bit.

Updated 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() */
    );
}

I also updated your demo link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM