我想让我的链接在我的固定标题改变滚动
代码似乎工作,如果你刷新页面,例如,如果你滚动到部分C和刷新页面和滚动它识别你在该部分,但由于某种原因,它似乎不做动态滚动。
https://jsfiddle.net/Lr53c1oh/1/<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
body, html {
padding: 0;
margin: 0;
height: 100%;
}
nav {
position: fixed;
top: 0;
width: 100%;
background: #f5f5f5;
text-align: center;
}
nav ul {
list-style: none;
display: inline-block;
}
nav ul li {
display: inline-block;
padding-right: 10px;
}
section {
height: 100%;
padding: 8rem;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
}
.sectionA {
background: orangered;
}
.sectionB {
background: steelblue;
}
.sectionC {
background: purple;
}
.sectionD {
background: black;
}
.active {
color: red;
}
</style>
</head>
<body>
<nav>
<ul>
<li class="sectionA-marker">Section A</li>
<li class="sectionB-marker">Section B</li>
<li class="sectionC-marker">Section C</li>
<li class="sectionD-marker">Section D</li>
</ul>
</nav>
<section class="sectionA">
<h2>Section A</h2>
</section>
<section class="sectionB">
<h2>Section B</h2>
</section>
<section class="sectionC">
<h2>Section C</h2>
</section>
<section class="sectionD">
<h2>Section D</h2>
</section>
</body>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript">
(function(){
var scrollTop = $(document).scrollTop();
var navHeight = $("nav").height();
var sectionElement = $("section");
$(document).on("scroll", function(){
sectionElement.each(function(){
var section = $(this);
if( section.offset().top < (scrollTop + navHeight) && (scrollTop + navHeight) < (section.offset().top + section.outerHeight()) ) {
var targetClass = "." + section.attr("class") + "-marker";
$("nav ul li").removeClass("active");
$(targetClass).addClass("active");
}
});
});
}());
</script>
</html>
校正后的小提琴
https://jsfiddle.net/Lr53c1oh/3/你需要在每次滚动事件中获取scrollTop的当前值
$(document).on("scroll", function(){
var scrollTop = $(document).scrollTop();
//rest of the code
编辑
对不起,我的第一个答案很懒;
你的问题发生了,因为你试图比较每个部分的顶部不是与屏幕的当前位置,而是你得到的位置当页面加载。
事件应该是这样的
$(document).on("scroll", function(){
// get new value of scrollTop after each event call
scrollTop = $(document).scrollTop();
sectionElement.each(function(){
var section = $(this);
if( section.offset().top < (scrollTop + navHeight) && (scrollTop + navHeight) < (section.offset().top + section.outerHeight()) ) {
var targetClass = "." + section.attr("class") + "-marker";
$("nav ul li").removeClass("active");
$(targetClass).addClass("active");
}
});
});