Jquery 在到达锚点后编辑我的 CSS 时如何更改?

How to change when Jquery edits my CSS upon reaching an anchor point?

我发现这段 Jquery 在到达锚点时会发生变化 CSS。

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

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

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

只需删除 - $(window).height()

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

if (scrollPosition > $("#someAnchor").position().top) { 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

并不是真的想成为答案,但它可能会有所帮助:

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

    $('#pos').html( 'y: '+scrollY+', a: '+$("#someAnchor").position().top + ', p: '+scrollPosition );
    if (!spam && (scrollPosition > $("#someAnchor").position().top)) {
        alert('hit it!');
        spam = true;
    }
});

一些html:

<div style="position:fixed; top:0; left:85%; width:15%; height:20px">
<span id="pos" style="font-family:Courier; font-size:0.5em; white-space:pre"></span>
</div>