Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

jquery - Get ID of reached area when scrolling

I need the ID of the container by scrolling through the page and when the container reaches the top of the page.

My Code so far

  $(window).scroll(function(){
    if($(window).scrollTop() >= $(".category-title").offset().top){
      var cat_id = "";
}
 });

I need the Id of div.category_title

THX

question from:https://stackoverflow.com/questions/65921315/get-id-of-reached-area-when-scrolling

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To achieve this you can use filter() and first() to retrieve the first .category-title elements which is next below the current scroll position, then prop() to get its id:

let $categoryTitles = $('.category-title');
let $output = $('#output span');

$(window).scroll(function() {
  let $topCat = $categoryTitles.filter((i, el) => $(el).offset().top > $(window).scrollTop()).first();
  $output.text($topCat.prop('id'));
}).scroll();
.category-title {
  height: 500px;
  border-bottom: 10px solid #C00;
}
#output {
  position: fixed;
  top: 5px;
  left: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">Id: <span></span></div>
<div class="category-title" id="A">A</div>
<div class="category-title" id="B">B</div>
<div class="category-title" id="C">C</div>
<div class="category-title" id="D">D</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...