【问题标题】:Scroll div position to element inside将 div 位置滚动到内部元素
【发布时间】:2018-10-20 18:21:05
【问题描述】:

我有一个 div 框,里面有不同的元素,我想从索引移动到其中的每一个,但我的代码只在第一次工作...

这是一个示例

$(document).on("click", ".goto", function(e) {
  var id = $(this).data('id');

  $('#panel').animate({
    scrollTop: $("#item_" + id).offset().top - 100
  }, 1000, 'swing');
});
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div style="width: 500px; height:500px; border:1px solid #eee; display:flex">
  <div style="width:100%; overflow-y:auto;" id="panel">

    <a href="#" id="item_a" style="margin:500px 0; display:block;">item1</a>
    <a href="#" id="item_b" style="margin:500px 0; display:block;">item2</a>
    <a href="#" id="item_c" style="margin:500px 0; display:block;">item3</a>

  </div>
</div>

<a href="#" class="goto" data-id="a">go to item1</a>
<a href="#" class="goto" data-id="b">go to item2</a>
<a href="#" class="goto" data-id="c">go to item3</a>

【问题讨论】:

    标签: jquery scrolltop


    【解决方案1】:

    尝试这样做:

     $('html, body').animate({
        scrollTop: $("#item_"+id).offset().top - 100
     }, 1000, 'swing');
    

    既然你要动画的是html和body,而不是面板。

    顺便说一句,我注意到这个问题可以用这个来回答:jQuery scroll to element ;)

    更新:

    我现在记得(再次测试后)我将你的更改为 .我还从您原来的主 div 中删除了一些样式。如果你不能像这样运行它,请告诉我,我们可以尝试其他方法。

    $(document).on("click", ".goto", function(e) {
      var id = $(this).data('id');
    
      $('html, body').animate({
        scrollTop: $("#item_" + id).offset().top - 100
      }, 1000, 'swing');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>
      <div id="panel">
    
        <div id="item_a" style="margin:500px 0; display:block;">item1</div>
        <div id="item_b" style="margin:500px 0; display:block;">item2</div>
        <div id="item_c" style="margin:500px 0; display:block;">item3</div>
    
      </div>
    </div>
    
    <a href="#" class="goto" data-id="a">go to item1</a>
    <a href="#" class="goto" data-id="b">go to item2</a>
    <a href="#" class="goto" data-id="c">go to item3</a>

    【讨论】:

    • 不工作...点击索引没有任何反应
    • @FireFoxII 你的 HTML 只有这个?我昨天使用了 jsfidde,它对我有用,但我只使用了你提供的代码。如果您的页面中有更多内容,则可能会受到影响。
    • 是的,这是……你能提供一个 sn-p 或一个 jsfiddle 吗?
    • 为什么会这样?你必须使用我的 div 结构。我有一个索引,我的面板 div 必须根据点击滚动...使用您的示例,我必须始终转到页面底部,我知道这是有效的...
    • 即使使用您的示例,我也需要转到页面底部。您的菜单可能位于面板上方。你可以保持你的风格并尝试将 元素更改为
      你试过了吗?
    猜你喜欢
    • 2021-09-02
    • 2018-02-09
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多