Javascript 如何在溢出隐藏的 div 中滚动到某个当前不可见的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11301841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:22:57  来源:igfitidea点击:

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

javascriptjqueryscroll

提问by k0pernikus

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.

我有一个溢出隐藏 div 中的元素列表。因此,并非所有元素都可见。现在,如果一个元素被激活,它应该在 div 中可见。

How do I scroll to the active element using jQuery?

如何使用 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>

The element that should become visible:

应该可见的元素:

var scrollToEl = $("div.element.active");

回答by sachleen

You can set the scrollTopof the wrapper div to be the topof the positionof the active element.

您可以将scrollTop包装器 divtopposition设置为活动元素的 。

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

DEMO

演示

回答by VisioN

Maybe you are looking for scrollIntoViewmethod.

也许您正在寻找scrollIntoView方法。

scrollToEl[0].scrollIntoView();

DEMO:http://jsfiddle.net/yuFk5/14/

演示:http : //jsfiddle.net/yuFk5/14/