gpt4 book ai didi

javascript - 事件链接适用于页面刷新但不适用于滚动?

转载 作者:太空宇宙 更新时间:2023-11-04 16:28:15 24 4
gpt4 key购买 nike

我正在尝试让固定标题中的链接在滚动时更改。

如果您刷新页面,例如,该代码似乎可以工作如果您滚动到 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>

最佳答案

这是更正后的 fiddle

https://jsfiddle.net/Lr53c1oh/3/

每次滚动事件时都需要获取scrollTop的当前值

$(document).on("scroll", function(){
var scrollTop = $(document).scrollTop();
//rest of the code

关于javascript - 事件链接适用于页面刷新但不适用于滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40040580/

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