首页 > 解决方案 > 每次点击页面顶部时如何检测正确的div数据属性

问题描述

我正在处理下面的代码。为什么我无法在向下或向上滚动时检测到哪个 div 到达页面顶部?

$(window).scroll(function() {
  $(".container").each(function() {
    var $that = $(this);
    var po = $(this).offset().top;
    if (po >= 0 && po <= 300) {
      console.log($that.data('map'));
    }
  });
});
.container {
  height: 690px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" data-map="One">One</div>
<div class="container" data-map="Two">Tow</div>
<div class="container" data-map="Three">Three</div>
<div class="container" data-map="Four">Four</div>
<div class="container" data-map="Five">Five</div>

标签: javascriptjquery

解决方案


你需要使用$(window).scrollTop();以及$that.outerHeight()

$(window).scroll(function() {
  var windowScrollTop = $(this).scrollTop(); // window scroll top
  $(".container").each(function() {
    var $that = $(this);
    var po = $that.offset().top;
    var poHeight = $that.outerHeight(true); // the height of the element
    var distanceTop = 100; // the distance from top to run the action .. it can be 0 if you want to run the action when the element hit the 0 top 
    if (windowScrollTop + distanceTop >= po && windowScrollTop + distanceTop <= po + poHeight) {
      
      if(!$that.hasClass('red')){ // if element dosen't has class red
        console.log($that.data('map'));
        $(".container").not($that).removeClass('red'); // remove red class from all
        $that.addClass('red'); // add red class to $that
      }
      
    }
  });
}).scroll(); // run the scroll onload
.container {
  height: 690px;
}
.container.red{
  background : red;
  color : #fff;
  font-size: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" data-map="One">One</div>
<div class="container" data-map="Two">Two</div>
<div class="container" data-map="Three">Three</div>
<div class="container" data-map="Four">Four</div>
<div class="container" data-map="Five">Five</div>


推荐阅读