【问题标题】:How to scroll to specific item using jQuery?如何使用 jQuery 滚动到特定项目?
【发布时间】:2011-02-23 18:05:30
【问题描述】:

我有一个带有垂直滚动条的大桌子。 我想使用 jQuery/JavaScript 滚动到此表中的特定行。

是否有内置方法可以做到这一点?

Here is a little example to play with.

div {
    width: 100px;
    height: 70px;
    border: 1px solid blue;
    overflow: auto;
}
<div>
    <table id="my_table">
        <tr id='row_1'><td>1</td></tr>
        <tr id='row_2'><td>2</td></tr>
        <tr id='row_3'><td>3</td></tr>
        <tr id='row_4'><td>4</td></tr>
        <tr id='row_5'><td>5</td></tr>
        <tr id='row_6'><td>6</td></tr>
        <tr id='row_7'><td>7</td></tr>
        <tr id='row_8'><td>8</td></tr>
        <tr id='row_9'><td>9</td></tr>
    </table>
</div>

【问题讨论】:

    标签: javascript jquery scroll


    【解决方案1】:

    您可以使用the jQuery scrollTo plugin 插件:

    $('div').scrollTo('#row_8');
    

    【讨论】:

    • 该链接不再可用。你能更新一下吗?
    【解决方案2】:

    很简单。 无需插件

    var $container = $('div'),
        $scrollTo = $('#row_8');
    
    $container.scrollTop(
        $scrollTo.offset().top - $container.offset().top + $container.scrollTop()
    );
    
    // Or you can animate the scrolling:
    $container.animate({
        scrollTop: $scrollTo.offset().top - $container.offset().top + $container.scrollTop()
    });​
    

    这是working example

    Documentation for scrollTop.

    【讨论】:

    • 如果容器有滚动条,则需要考虑scrollTop:scrollTo.offset().top - container.offset().top + container.scrollTop()
    • 您可以使用 $(document).scrollTop(value) 滚动整个窗口 - 底层 jquery 代码为您解决浏览器问题。
    • 如果您希望 scrollTo 居中而不是顶部:scrollTo.offset().top - container.offset().top + container.scrollTop() - (container.height()/2)
    • element.scrollIntoView() - 这就是所有需要的。动画是标准化的。见developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
    • 请注意,代码块的最后有一个“不可见”字符。该字符在 Edge、chrome 中被认为是无效的。 - 复制粘贴
    【解决方案3】:

    我自己设法做到了。不需要任何插件。看看我的gist

    // Replace #fromA with your button/control and #toB with the target to which     
    // You wanna scroll to. 
    //
    $("#fromA").click(function() {
        $("html, body").animate({ scrollTop: $("#toB").offset().top }, 1500);
    });
    

    【讨论】:

    • 你的单行要点,加上动画,正是我所需要的。谢谢!
    • No need for any plugins ??但是你使用 jQuery!这是一个巨大的图书馆,甚至不是一个插件。
    • 我提醒您,除了 jquery 库参考之外,您不需要添加参考。加上 jquery 是一种行业标准。你为什么不使用它?如果没有 jquery,这可能是完全可行的,但它仍然需要有人为解析部分编写大量代码。感觉适得其反。而且仅仅为了滚动到一个令人毛骨悚然的 div 而编写一个完整的插件会适得其反。
    【解决方案4】:

    我意识到这并不能解决在容器中滚动的问题,但人们发现它很有用:

    $('html,body').animate({scrollTop: some_element.offset().top});
    

    我们同时选择 html 和 body,因为文档滚动条可能在其中一个上,并且很难确定哪个。对于现代浏览器,您可以使用$(document.body)

    或者,转到页面顶部:

    $('html,body').animate({scrollTop: 0});
    

    或者没有动画:

    $(window).scrollTop(some_element.offset().top);
    

    或者...

    window.scrollTo(0, some_element.offset().top); // native equivalent (x, y)
    

    【讨论】:

    • 你好@infensus你能给我一个这个原因我的工作不工作的例子吗?我用 var section2=$('#section-2'); $('html,body').animate({scrollTop: section2.offset().top});
    • 看起来不错 - 你确定 section2 存在吗?做 console.log(section2.length);并确保它不为 0。稍后将举例说明。
    • 为什么是$('html,body')?他只需要在特定的容器中。接受的答案对我来说更好。我有类似的情况,如所问的问题,你的回答对我不起作用。
    • @Petroff 奇怪的是,当我写这篇文章时,我没有注意到元素在滚动容器中。我会保留我的答案,因为由于问题标题,人们从谷歌搜索来到这里滚动正文
    【解决方案5】:

    不知道为什么没有人说显而易见的,因为有一个内置的 javascript scrollTo 函数:

    scrollTo( $('#element').position().top );
    

    Reference.

    【讨论】:

    • scrollTo 需要两个参数,你只写了一个。
    • ... 它在窗口对象上被调用。
    【解决方案6】:

    我同意 Kevin 和其他人的观点,为此使用插件是没有意义的。

    window.scrollTo(0, $("#element").offset().top);
    

    【讨论】:

    • 对于应该非常简单的事情,我已经花了很长时间在网上的其他解决方案上,但是这个简单的一个班轮正是我所需要的。
    • 需要注意的是,这种方式适用于整个窗口。如果你想滚动有 overflow:scroll 的内容,那么这将不起作用。
    【解决方案7】:

    我结合了其他人发布的内容。简单流畅

     $('#myButton').click(function(){
            $('html, body').animate({
                scrollTop: $('#scroll-to-this-element').position().top },
                1000
            );
        });
    

    【讨论】:

    • @AnriëtteMyburgh 我不确定 position() 是否适用于所有浏览器。你有没有在其他人身上试过,看看它是否有效?或者我可以看看你正在使用的代码,看看是否还有其他问题?
    【解决方案8】:

    与这里大多数人的建议相反,我建议您使用插件来制作动画。仅仅为 scrollTop 设置动画还不足以提供流畅的用户体验。原因见my answer here

    这些年来我尝试了许多插件,但最终我自己写了一个。您可能想试一试:jQuery.scrollable。使用它,滚动动作变成了

    $container.scrollTo( targetPosition );
    

    但这还不是全部。我们也需要固定目标位置。您在其他答案中看到的计算,

    $target.offset().top - $container.offset().top + $container.scrollTop()
    

    大部分有效,但并不完全正确。它没有正确处理滚动容器的边框。目标元素向上滚动太多,超出了边框的大小。 Here is a demo.

    因此,计算目标位置的更好方法是

    var target = $target[0], 
        container = $container[0];
    
    targetPosition = $container.scrollTop() + target.getBoundingClientRect().top - container.getBoundingClientRect().top - container.clientTop;
    

    再一次,看看at the demo 看看它的实际效果。

    对于返回目标位置并适用于窗口和非窗口滚动容器的函数,请随意使用this gist。里面的 cmets 解释了位置是如何计算的。

    一开始,我说过最好使用插件来进行动画滚动。但是,如果您想在没有过渡的情况下跳转到目标,则不需要插件。请参阅answer by @James,但如果容器周围有边框,请确保正确计算目标位置。

    【讨论】:

      【解决方案9】:

      您可以在 javascript 中使用scrollIntoView() 方法。 给id.scrollIntoView();

      例如

      row_5.scrollIntoView();
      

      【讨论】:

      • 如何制作动画?
      • 不需要动画。当您使用 scrollIntoView() 时,控件将自动滚动以使其显示在视图中。
      【解决方案10】:

      对于它的价值,这就是我设法为一个通用元素实现这种行为的方法,该元素可以在带有滚动的 DIV 内(不知道容器)

      它创建一个目标元素高度的假输入,然后将焦点放在它上面,无论您在可滚动层次结构中有多深,浏览器都会处理其余部分。像魅力一样工作。

      var $scrollTo = $('#someId'),
      inputElem = $('<input type="text"></input>');
      
      $scrollTo.prepend(inputElem);
      inputElem.css({
        position: 'absolute',
        width: '1px',
        height: $scrollTo.height()
      });
      inputElem.focus();
      inputElem.remove();
      

      【讨论】:

        【解决方案11】:

        滚动元素到容器中心

        将元素带到容器的中心。

        DEMO on CODEPEN

        JS

        function scrollToCenter() {
          var container = $('.container'),
            scrollTo = $('.5');
        
          container.animate({
            //scrolls to center
            scrollTop: scrollTo.offset().top - container.offset().top + scrollTo.scrollTop() - container.height() / 2
          });
        }
        

        HTML

        <div class="container">
           <div class="1">
            1
          </div>
          <div class="2">
            2
          </div>
          <div class="3">
            3
          </div>
          <div class="4">
            4
          </div>
          <div class="5">
            5
          </div>
          <div class="6">
            6
          </div>
          <div class="7">
            7
          </div>
          <div class="8">
            8
          </div>
          <div class="9">
            9
          </div>
          <div class="10">
            10
          </div>
        
        
        </div>
        <br>
        <br>
        <button id="scroll" onclick="scrollToCenter()">
          Scroll
        </button>
        

        css

        .container {
          height: 60px;
          overflow-y: scroll;
          width 60px;
          background-color: white;
        }
        

        它不精确到中心,但你不会在更大的元素上识别它。

        【讨论】:

          【解决方案12】:

          您可以通过 jQueryJavaScript 滚动 只需要两个元素 jQuery 和这段 JavaScript 代码:

          $(function() {
            // Generic selector to be used anywhere
            $(".js-scroll-to-id").click(function(e) {
          
              // Get the href dynamically
              var destination = $(this).attr('href');
          
              // Prevent href=“#” link from changing the URL hash (optional)
              e.preventDefault();
          
              // Animate scroll to destination
              $('html, body').animate({
                scrollTop: $(destination).offset().top
              }, 1500);
            });
          });
          

          $(function() {
            // Generic selector to be used anywhere
            $(".js-scroll-to-id").click(function(e) {
          
              // Get the href dynamically
              var destination = $(this).attr('href');
          
              // Prevent href=“#” link from changing the URL hash (optional)
              e.preventDefault();
          
              // Animate scroll to destination
              $('html, body').animate({
                scrollTop: $(destination).offset().top
              }, 1500);
            });
          });
          #pane1 {
            background: #000;
            width: 400px;
            height: 400px;
          }
          
          #pane2 {
            background: #ff0000;
            width: 400px;
            height: 400px;
          }
          
          #pane3 {
            background: #ccc;
            width: 400px;
            height: 400px;
          }
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
          <ul class="nav">
            <li>
              <a href="#pane1" class=" js-scroll-to-id">Item 1</a>
            </li>
            <li>
              <a href="#pane2" class="js-scroll-to-id">Item 2</a>
            </li>
            <li>
              <a href="#pane3" class=" js-scroll-to-id">Item 3</a>
            </li>
          </ul>
          <div id="pane1"></div>
          <div id="pane2"></div>
          <div id="pane3"></div>
          <!-- example of a fixed nav menu -->
          <ul class="nav">
            <li>
              <a href="#pane3" class="js-scroll-to-id">Item 1</a>
            </li>
            <li>
              <a href="#pane2" class="js-scroll-to-id">Item 2</a>
            </li>
            <li>
              <a href="#pane1" class="js-scroll-to-id">Item 3</a>
            </li>
          </ul>

          【讨论】:

            【解决方案13】:

            我做了这个组合。它为我工作。但如果点击就会面临一个问题 移动那个 div 尺寸太大,场景滚动不向下到这个 特定的 div。

             var scrollDownTo =$("#show_question_" + nQueId).position().top;
                    console.log(scrollDownTo);
                    $('#slider_light_box_container').animate({
                        scrollTop: scrollDownTo
                        }, 1000, function(){
                    });
            
                    }
            

            【讨论】:

              猜你喜欢
              • 2011-09-06
              • 1970-01-01
              • 1970-01-01
              • 2011-03-14
              相关资源
              最近更新 更多