固定导航添加类依赖于节

时间:2018-04-24 07:56:25

标签: javascript jquery

我需要将类添加到标题依赖于它的节。这是我的代码

.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

2 个答案:

答案 0 :(得分:1)

我玩了一些你的代码,最后来到了这个:

&#13;
&#13;
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;
&#13;
&#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>