【问题标题】:Open a link and autoscroll to specific div using jQuery使用 jQuery 打开链接并自动滚动到特定的 div
【发布时间】:2015-09-17 00:40:47
【问题描述】:

我有这段代码,当您打开链接时,它会滚动到该页面上的特定 div。

collection.html

<a id='about' href="index.html">about</a>

index.html

<div id='#moreInfo>contents here</div>

<script>
   $(document).ready(function(){
          $('html, body').animate({
             scrollTop: $("#moreInfo").offset().top
           }, 1000);
   })
</script>

我的问题是每当我加载 index.html 时,它总是滚动到 moreInfo div。我想要的是当我在 collection.html 上并单击 about 链接时,它将重定向到 index.html 然后滚动顺利到 moreInfo div。

我将不胜感激。

【问题讨论】:

    标签: javascript jquery html autoscroll


    【解决方案1】:

    一个简单的方法就是让你的链接指向一个位置哈希。

    <a id='about' href="index.html#moreInfo">about</a>
    

    然后,在您的 JavaScript 中,您可以检查该人是否来自该链接。

       $(document).ready(function(){
          if (window.location.hash == "#moreInfo") {
            $('html, body').animate({
               scrollTop: $("#moreInfo").offset().top
             }, 1000);
          }
       });
    

    【讨论】:

    • 不应该是&lt;a id='about' href="index.html#moreInfo"&gt;about&lt;/a&gt; ...没有“/”吗?
    • @DelightedD0D 没错。我也不确定这个解决方案是否有效,因为如果我没记错的话,浏览器会在 javascript 有机会平滑滚动之前自动捕捉到 moreInfo 部分。
    • 是的@DelightedD0D,你是对的,我已经编辑过了。我对马克西米利安的评论也很好奇,因为我没有完全按原样测试它。尽管目前我在生产代码中确实有非常相似的事情在为我工作。
    • 其实@MaximillianLaumeister 是对的,see this test 它会在指定位置加载重置到顶部并向下滚动。 OP 可以省去滚动,只需加载到该部分……恕我直言,这将不那么刺耳
    • @DelightedD0D 也许我对平滑滚动的理解是错误的,但这就是我在参加您的测试时所得到的......速度也可以放慢以提供帮助随着过渡——尝试将其设为 3000,既好又慢。感谢您将测试放在一起:-)
    【解决方案2】:

    您可以通过在链接 URL 上设置 GET 参数然后在下一页加载时读取该参数来做到这一点:

    collection.html

    <a id='about' href="index.html?scrollTo=moreInfo">about</a>
    

    index.html

    <script>
       $(document).ready(function(){
              var scrollTo = getParameterByName('scrollTo');
              if(scrollTo!=''){
                  $('html, body').animate({
                     scrollTop: $("#"+scrollTo).offset().top
                   }, 1000);
              }
       });
    
       function getParameterByName(name) {
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
                results = regex.exec(location.search);
            return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        }
    </script>
    

    【讨论】:

      【解决方案3】:

      仅使用 html 即可实现平滑滚动

      您的页面包含类似的 div

      <div id="sample">
      </div>
      

      你必须使用滚动到这个 div

      <a href="#sample">click here to scroll</a>
      

      只需在您的 css 中使用以下代码

      <style>
          html {
              scroll-behavior: smooth;
          }
      
      </style>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多