【问题标题】:Scroll to a specific div滚动到特定的 div
【发布时间】:2014-07-10 06:47:54
【问题描述】:

我很少有 divs .posts 有一个 attr data-id 对应于 mysql DB id

<div class="posts" data-id="1"></div>
<div class="posts" data-id="2"></div>

现在,如果我想滚动到特定的div,我只知道data-id。 我将如何滚动到它? 我的JSFiddle is here。 任何人都可以举一个 JSFiddle 的例子吗?

【问题讨论】:

标签: javascript jquery html scroll


【解决方案1】:

我认为这会有所帮助$(".element").attr("any-attribute-of-ur-elem"); 在您的情况下,它看起来像:$(".post").attr("data-id") 你可以滚动到那个帖子。 试试这个:

    $(document).ready(function (){
        $("#button").click(function (){
            $('html, body').animate({
               scrollTop: $(".post[data-id="+yourID+"]").offset().top
            }, 2000);
        });
    });

【讨论】:

    【解决方案2】:

    您使用链接锚和 JQuery。 只需为您的链接提供“滚动”类并在头部使用以下代码:

    $(function() {
      // Listen for a click event on the anchor
      $('.scroll').click(function(event) {
      
        // Prevent the jump to target that is default browser behavior
        event.preventDefault();
        
        // Animate the scrollTop property of the scrollParent to the top offset 
        // of the target element. In this case, we have an animation duration of 1000ms(1 second).
        $('html').animate({
          scrollTop: $(this.hash).offset().top
        }, 1000);
      });
    });
    /* Just for demo purposes */
    .post {
      margin: 100vh 0;
      background: yellow;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <a href="#anchor" class="scroll">Go To Div 8</a>
    <div class="post" id="anchor">Scroll to me</div>

    【讨论】:

    • 添加 preventDefault 并不总是一种健康的做法,它可能会破坏其他功能。避免这种情况
    • event.preventDefault();被添加删除锚的默认功能,如果你不添加它,锚将添加到导航(http://example.com/#anchor)并且可能有一个bug渲染。跨度>
    【解决方案3】:

    如果您有一个带有name 的锚点,则不需要javascript。

    &lt;a href="#post8"&gt;Div to post 8&lt;/a&gt; 滚动到&lt;a name="post8"&gt;&lt;/a&gt;

    【讨论】:

      【解决方案4】:

      您可以使用 jQuery.ScrollTo 插件:https://github.com/flesler/jquery.scrollTo

      在这个链接中你可以找到演示http://demos.flesler.com/jquery/scrollTo/

      $(function() {             
          $('body').scrollTo($('div[data-id=1]'), 1000); //scroll to div 1        
      });
      

      HTML:

      <div class="posts" data-id="1"></div>
      

      【讨论】:

      • 请提供代码来演示这个插件的使用。现在,它不是很有用,因为链接(尤其是演示链接)可能会失效,我们将得不到太多答案。
      【解决方案5】:

      我在这里看到了很多 jQuery 和 Javascript,简单的 CSS 可以帮助你!

      html,body {
          scroll-behavior: smooth;
      }
      

      要执行此操作,请使用链接并为其提供一个带有您正在滚动到的元素 id 的 href:

      <a href="sectionOne">Section One</a>
      
      <div id="sectionOne">
          <h2>Section One</h2>
      </div>
      

      但并非所有浏览器都支持scroll-behavior 属性,在这种情况下,我建议选择靠近顶部的答案;)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-16
        • 2017-08-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多