繁体   English   中英

打开一个链接并使用jQuery自动滚动到特定的div

[英]Open a link and autoscroll to specific div using jQuery

我有这段代码,当您打开链接时,它将滚动到该页面上的特定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和我点击有关链接我要的是,它会重定向到的index.html然后平稳滚动到moreInfo股利。

我将不胜感激。

一种简单的方法是让您的链接指向位置哈希。

<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);
      }
   });

您可以通过在链接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>

您可以仅使用html来实现平滑滚动

您的页面包含div之类的

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

您必须使用滚动到该div

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

并简单地在CSS中使用以下代码

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

</style>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM