最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change active tab on navbar when scrolling until a component is visible? - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 3

Replying 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.

发布评论

评论列表(0)

  1. 暂无评论