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

时间:2016-05-03 18:53:54

标签: javascript jquery css anchor

我发现这条Jquery在到达锚点时更改了CSS。

edge_n_grams

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

3 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

希望这对您有用:

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

答案 2 :(得分:0)

并非真正意义上的答案,但它可能会有所帮助:

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>