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

javascript - How to scroll within an overflow hidden div to a certain currently invisible element?

I have a list of elements within a overflow hidden div. So not all elements are visible. Now, if an element gets activated, it should become visible within the div.

How do I scroll to the active element using jQuery?

It's merely a convenience that the last element has the active class. It will be toggled dynamically.

 var scrollToEl = $("div.element.active");
 console.log(zoomToEl);
 #main,
 #sidebar {
   height: 200px;
 }
 #wrapper {
   width: 190px;
   float: left;
   background: grey;
   overflow: auto;
   overflow-x: hidden;
 }
 #sidebar div.element {
   height: 150px;
   width: 150px;
   background-color: green;
   margin-bottom: 10px;
 }
 #sidebar div.element.active {
   background-color: red;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
  <div id="wrapper" class="sidebar">
    <div id="sidebar">
      <div class="element" data-slide-id="0">a
      </div>
      <div class="element" data-slide-id="1">b
      </div>
      <div class="element" data-slide-id="2">c
      </div>
      <div class="element" data-slide-id="3">d
      </div>
      <div class="element" data-slide-id="4">e
      </div>
      <div class="element" data-slide-id="5">f
      </div>
      <div class="element" data-slide-id="6">g
      </div>
      <div class="element active" data-slide-id="7">h
      </div>
    </div>
  </div>
</div>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can set the scrollTop of the wrapper div to be the top of the position of the active element.

$("#wrapper").scrollTop($("#wrapper").scrollTop() + $("div.element.active").position().top);

DEMO


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

1.4m articles

1.4m replys

5 comments

56.9k users

...