我需要将类添加到标题依赖于它的节。这是我的代码
.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
JSFiddle link
.second-section
答案 0 :(得分:1)
我玩了一些你的代码,最后来到了这个:
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");
};
&#13;
.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;
}
&#13;
<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>
&#13;
这是你想要达到的目标吗? 请注意,我使用了vanilla JavaScript。
我希望它有所帮助。
答案 1 :(得分:0)
请参阅this
当用户滚动到selected
时,这会将second-section
类添加到您的导航栏。
<强> JS:强>
var target = $(".second-section").offset().top;
var interval = setInterval(function() {
if ($(window).scrollTop() >= target) {
$('#nav').addClass('selected');
}
}, 0);
<强> CSS:强>
.selected {
background-color:blue;
}
从here获取最新版本的jQuery - 小提琴使用jQuery版本3.3.1
修改强>
将此添加到Wordpress主题中的footer.php文件中。
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script type="text/javascript">
var target = $(".second-section").offset().top;
var interval = setInterval(function() {
if ($(window).scrollTop() >= target) {
$('#nav').addClass('selected');
}
}, 0);
</script>