我编码如下:
// Click Function
$('body').on('click', 'a', function() {
$('a.active').removeClass('active');
$(this).addClass('active');
});
// Scroll Function
const sectionIsInViewport = document.querySelector('section');
observer = new IntersectionObserver((callback) => {
console.log('This section is now in the viewport.');
});
observer.observe(sectionIsInViewport);
* {
margin: 0;
padding: 0;
font-family: sans-serif;
font-size: 30px;
text-decoration: none;
color: inherit;
}
body {
display: flex;
cursor: default;
}
#left,
#right {
width: 50%;
height: 100vh;
overflow-y: scroll;
scroll-behavior: smooth;
}
#left {
background-color: rgb(220, 220, 220);
}
#right {
background-color: rgb(200, 200, 200);
}
.media {
padding: 10px;
padding-bottom: 0;
}
.media:nth-last-child(1) {
margin-bottom: 10px;
}
img {
display: block;
width: 100%;
}
.link {
cursor: pointer;
}
.active {
background-color: black;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="left">
<a class="link active" href="#landscapes">Landscapes</a>
<a class="link" href="#cats">Cats</a>
<a class="link" href="#food">Food</a>
</div>
<div id="right">
<section id="landscapes">
<article class="media">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/8d/Freudenberg_sg_Switzerland.jpg">
</article>
<article class="media">
<img src="https://i.pinimg.com/originals/ae/99/54/ae995473d0b73efd9b32b5cd029d9396.jpg">
</article>
<div class="media">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/Rural_landscape.JPG/1200px-Rural_landscape.JPG">
</div>
<article class="media">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/8d/Freudenberg_sg_Switzerland.jpg">
</article>
</section>
一般来说,它有效。但是:如果您滚动到正确的区域,.active链接应该会自动更新。因此,如果您滚动到该部分#food,则相应的链接应该是.active。
我尝试使用 Intersection Observer,但我不确定它是否是最好的工具。使用 React 有意义吗?如果是,为什么?
有人可以帮我吗?会非常感激。<3<3<3
森栏
相关分类