我发现这段Jquery在到达锚点时会更改CSS。

$(window).on("scroll", function() {
    var scrollPosition = scrollY || pageYOffset;

    if (scrollPosition > $("#someAnchor").position().top - $(window).height()) {
        alert("run code here");
    }
});


问题在于,当屏幕的底部到达锚点时会这样做,但是当屏幕顶部到达锚点时,它需要运行代码。我该怎么做呢?

最佳答案

希望这对您有效:

var ranOffsetCode = false

$(window).on("scroll", function() {

  var docScrollTop = $(document).scrollTop(); // Figure out how far we scrolled.
  var someAnchorTop = $('#someAnchor').offset().top - $('#someAnchor').height(); // Figure out how far down the element is on the page

  if (docScrollTop >= someAnchorTop) { // If we scrolled up to or past the element, fire this
    if (ranOffsetCode === false) { // This makes sure we only run the function once and not every scroll
      ranOffsetCode = true;
      console.log('run code here'); // Functional code to execute after we scrolled down this far.
    }
  }
  else {
    ranOffsetCode = false;
  }

});


Demo

10-06 07:34