简体   繁体   English

滚动时如何将菜单置于顶部,并通过突出显示相应的菜单链接来选择适当的滚动部分

[英]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. 预期当我滚动到链接2数据时,如果我单击链接,则链接2菜单选项卡也应突出显示并也应滚动到相应部分。

Here it is what I tried: 这是我尝试过的:

demo Link 演示链接

HTML: 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. 我已将您的js更新为滚动到内容部分并突出显示滚动条上的菜单项。 You also need to change your css a bit. 您还需要稍微更改CSS。

Updated JS 更新了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 我还更新了您的演示链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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