Open a link and autoscroll to specific div using j

2019-09-11 12:02发布

问题:

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>