繁体   English   中英

滚动菜单活动类-带有页边距的问题

[英]Menu active class on scrolling - Issue with section margins

我正在尝试做的是:

当用户在我的网站上上下滚动(单页,多个部分)时,菜单将突出显示该用户当前所在页面的哪个部分。

我做了什么:

我有一个工作菜单,以便当链接的部分当前滚动到该菜单时,它将把类更改为“活动”。

问题:

每个部分的上边距约为50-100像素。 当前的javascript代码无法处理此问题,而是如果用户位于两个部分之间,则将其从所有菜单项中完全删除。

JS小提琴: http //jsfiddle.net/d4yqA/3/

HTML:

<div id="headerWrapperFixed">
    <div id="headerFixed">
        <div id="fixedMenu">
            <ul>
                <li><a href="#home">Home</a>

                </li>
                <li><a href="#about-us">About Us</a>

                </li>
                <li><a href="#pricing">Pricing</a>

                </li>
                </li>
            </ul>
        </div>
    </div>
</div>
<div id="home">
     <h1>HOME</h1>

</div>
<div id="about-us">
     <h1>ABOUT US</h1>

</div>
<div id="pricing">
     <h1>PRICING</h1>

</div>

CSS:

#headerWrapperFixed {
    top:0;
    position:fixed;
    height:30px;
    width:100%;
    background-color:RGB(38, 38, 38);
}
#headerFixed {
    width:1100px;
    height:30px;
    background-color:RGB(200, 200, 200);
}
#fixedMenu {
    position:relative;
    width:700px;
    height:30px;
}
#fixedMenu ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width:650px;
    height:30px;
}
#fixedMenu li {
    display: table-cell;
    width:120px;
    height:30px;
    text-align:center;
    vertical-align:middle;
}
li.active a, #fixedMenu li>a:hover, a.active {
    color:#FF0000 !important;
}
#home {
    height:800px;
    background-color:rgb(100, 100, 100);
    margin-top:100px;
}
#about-us {
    height:800px;
    background-color:rgb(200, 200, 200);
    margin-top:100px;
}
#pricing {
    margin-top:100px;
    height:800px;
}
h1 {
    margin:0;
    padding-top:50px;
}

Javascript:

$(window).scroll(function () {


    var scrollPos = $(document).scrollTop() + 40;
    $('#fixedMenu a').each(function () {
        var currLink = $(this);
        var refElement = $(currLink.attr("href"));
        if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
            $('#fixedMenu ul li').removeClass("active");
            currLink.addClass("active");
        } else {
            currLink.removeClass("active");
        }
    });

});

如果要在滚动到页边距时仅将活动类保留在当前部分上,只需将其添加到等式的右侧

 if (refElement.position().top <= scrollPos + 120 && refElement.position().top + refElement.height() > scrollPos + 0) {

或者,如果您要转到下一个,请从右侧减去它

 if (refElement.position().top <= scrollPos -120&& refElement.position().top + refElement.height() > scrollPos) {

暂无
暂无

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

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