Open a link and autoscroll to specific div using jQuery

我们两清 提交于 2019-12-24 16:16:39

问题


I have this code that when you open a link it will scroll to the specific div on that page.

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>

My problem is whenever I load the index.html, it always scrolls to the moreInfo div. What I want is when I'm on collection.html and I click on the about link, it will redirect to index.html then scroll smoothly to the moreInfo div.

I'll appreciate any answer.


回答1:


An easy way to do this is just to have your link point to a location hash.

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

Then, in your JavaScript you could just check if the person came from that link.

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



回答2:


You can do this by setting a GET parameter on the link URL then reading that parameter when the next page loads:

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:


You can achieve smooth scrolling using html only

your page contains div like

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

You have to scroll to this div using

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

and simply use below code in your css

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

</style>


来源:https://stackoverflow.com/questions/32620885/open-a-link-and-autoscroll-to-specific-div-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!