代码之家  ›  专栏  ›  技术社区  ›  Hendrik B.

当div到达页面顶部时如何记录

  •  0
  • Hendrik B.  · 技术社区  · 8 年前

      var distance = $('.img').offset().top;
        $window = $(window);
    
    $window.scroll(function() {
        if ( $window.scrollTop() >= distance ) {
            console.log("Div is now at the top of the site!")
        }
    });
    

    <div class="img">
            <img src="city.jpg">
            </div>
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Thijs    8 年前

    getBoundingClientRect()

    当在卷轴上工作时,最好将你想做的工作去掉阴影。请参阅此处了解更多信息: https://davidwalsh.name/javascript-debounce-function

    const
      contentDiv = document.getElementById('content-div');
      
    function onScrollHandler(event) {
      console.log(`Pixels from top: ${contentDiv.getBoundingClientRect().top}`);  
    }
    
    window.addEventListener('scroll', onScrollHandler);
    .vertical-space {
      height: 200vh;
    }
    
    .content-div {
      background-color: #333;
      color: #fff;
    }
    <div class="vertical-space"></div>
    <div id="content-div" class="vertical-space content-div">Now you see me</div>