admin管理员组文章数量:1435859
I have a navBar with multiple tabs which I can click and it scrolls me to the ponent (scrollToComponent), it also sets that tab as the active one.
I also want to do the oposite, scroll and when a ponent is visible it should mark the corresponding tab as the active one.
I found this fiddle, that demonstrates exactly what I need, but it uses Jquery, and the items that it scrolls to are not ponents, and all of them have the same height.
$(document).ready(function () {
$(document).on("scroll", onScroll);
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('#menu-center a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('#menu-center ul li a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
I have a navBar with multiple tabs which I can click and it scrolls me to the ponent (scrollToComponent), it also sets that tab as the active one.
I also want to do the oposite, scroll and when a ponent is visible it should mark the corresponding tab as the active one.
I found this fiddle, that demonstrates exactly what I need, but it uses Jquery, and the items that it scrolls to are not ponents, and all of them have the same height.
$(document).ready(function () {
$(document).on("scroll", onScroll);
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('#menu-center a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('#menu-center ul li a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
Share
Improve this question
edited Jun 19, 2020 at 19:31
Martin Pascale
asked Jun 16, 2020 at 18:34
Martin PascaleMartin Pascale
511 silver badge6 bronze badges
1 Answer
Reset to default 3Replying myself since it can be useful for someone on the future:
I made this codesandbox example using react-intersection-observer.
It has a custom hook that lets you know if the element is visible, then you would have to pare which element is on top, so you can decide which tab you want to set as the active one.
版权声明:本文标题:javascript - How to change active tab on navbar when scrolling until a component is visible? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745674714a2669781.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论