gpt4 book ai didi

javascript - 固定导航添加类依赖于部分

转载 作者:行者123 更新时间:2023-11-29 23:23:08 26 4
gpt4 key购买 nike

我需要将类添加到标题依赖于其依据的部分。这是我的代码

.navigation {
position: fixed;
background: white;
width: 400px;
height:15px;
border: 1px solid #000;
color: orange;
}

section {
display: block;
width: 100%;
height:200px;
}

.first-section {
background-color: black;
}

.second-section {
background-color: white;
}
<div id="nav" class="navigation">menu</div>

<section class="first-section" id="a"></section>
<section class="second-section" id="b"></section>
<section class="third-section" id="c"></section>

我想我需要一些 jQuery 代码来将类添加到 .navigation 时将它带到 .second-section JSFiddle link

最佳答案

我试了一下你的代码,最后得出了这个结论:

function style_in_section(elementId, styleClassName, sectionClassName) {
var pos = window.pageYOffset;
var element = document.getElementById(elementId);
var section = document.getElementsByClassName(sectionClassName)[0];
if ((pos >= section.offsetTop) && (pos < section.offsetTop + section.offsetHeight)) {
element.classList.add(styleClassName);
} else {
element.classList.remove(styleClassName);
}
}

window.onscroll = function() {
style_in_section("nav", "nav-black", "second-section");
style_in_section("nav", "nav-gray", "third-section");
};
.navigation {
position: fixed;
width: 400px;
height: 15px;
border: 1px solid #000;
background: white;
color: orange;
}


/* I added styles here */

.nav-black {
background: black;
}

.nav-gray {
background: gray;
}

section {
display: block;
width: 100%;
height: 600px;
}

.first-section {
background-color: black;
}

.second-section {
background-color: white;
}

.third-section {
background-color: yellow;
}
<div id="nav" class="navigation">menu</div>
<section class="first-section" id="a"></section>
<section class="second-section" id="b"></section>
<section class="third-section" id="c"></section>

这就是你想要实现的目标吗?
请注意,我使用的是原生 JavaScript。

希望对你有帮助。

关于javascript - 固定导航添加类依赖于部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49996286/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com