JavaScript/jQuery add class when element comes into viewport?

后端 未结 2 2029
囚心锁ツ
囚心锁ツ 2021-01-20 23:34

Is there a way to add a class when the element that I want to apply the class to comes into the viewport? Or when the bottom of the screen is a certain distance past the top of

相关标签:
2条回答
  • 2021-01-20 23:40

    You could do something like this: (See CodePen for implementation)

    Function taken from here: Check if element is visible after scrolling

    CodePen

    $(window).on('scroll', function() {
      $(".graph").each(function() {
        if (isScrolledIntoView($(this))) {
          $(this).find(".graph-line").addClass("graph-75");
          $(this).find(".graph-line-2").addClass("opacity");
        }
      });
    });
    
    function isScrolledIntoView(elem) {
      var docViewTop = $(window).scrollTop();
      var docViewBottom = docViewTop + $(window).height();
    
      var elemTop = $(elem).offset().top;
      var elemBottom = elemTop + $(elem).height();
    
      return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
    }
    

    Altough this is not perfect, it should point you into the right direction.

    0 讨论(0)
  • 2021-01-20 23:42

    You're on the right track, I think if you use the scroll event with a function such as the answer to this similar question:

    Check if element is visible after scrolling

    Hope that helps :)

    0 讨论(0)
提交回复
热议问题