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
196 views
in Technique[技术] by (71.8m points)

javascript - How to scroll to nth-child using jquery?

Hello using Jquery how can i scroll an element (with overflow) to children element ?

<span id="gran">
 <span id="parent">
  <div class="a">
   Casa
  </div>
  <div class="a">
   Casa
  </div>
  <div class="a">
   Casa
  </div>
  <div class="a">
   Casa
  </div>
  <div class="a">
   Casa
  </div>
 </span>
</span>

#gran {
overflow: auto;
}

I want to scroll #gran to third element with class a so i tried this but doesn't work:

 $("#gran").scrollTo('#parent > div:nth-child(3)'); 

I hope in your help :) Thanks a lot and sorry for my english

question from:https://stackoverflow.com/questions/65647905/how-to-scroll-to-nth-child-using-jquery

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

1 Reply

0 votes
by (71.8m points)

This is how it can be done

  • You need to set max-height with overflow : auto to let the element scrollable without that it will keep extending without scrollbar .. if you need to use the document/body scrollbar use $('body , html') Smooth scroll to div id jQuery

  • You need to use animate() function with scrollTop and offset()/position()

//$("#gran").scrollTo('#parent > div:nth-child(3)');

$(document).ready(function(){
  $('#gran').animate({
      scrollTop: - $('#gran').offset().top + $("#parent > div:nth-child(3)").offset().top
  }, 2000);
});
#to_remove{
  background : red;
  height : 100px;

}

#gran {
overflow: auto;
max-height : 500px;
}
.a{
  height : 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="to_remove"></div>

<div id="gran">
 <div id="parent">
  <div class="a">
   Casa 1
  </div>
  <div class="a">
   Casa 2
  </div>
  <div class="a">
   Casa 3
  </div>
  <div class="a">
   Casa 4
  </div>
  <div class="a">
   Casa 5
  </div>
 </div>
</div>

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

...