简体   繁体   English

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

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

I have this code that when you open a link it will scroll to the specific div on that page. 我有这段代码,当您打开链接时,它将滚动到该页面上的特定div。

collection.html collection.html

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

index.html 的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. 我的问题是,每当我加载index.html时 ,它总是滚动到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. 当我在collection.html和我点击有关链接我要的是,它会重定向到的index.html然后平稳滚动到moreInfo股利。

I'll appreciate any answer. 我将不胜感激。

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. 然后,在您的JavaScript中,您可以仅检查该人是否来自该链接。

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

You can do this by setting a GET parameter on the link URL then reading that parameter when the next page loads: 您可以通过在链接URL上设置GET参数,然后在下一页加载时读取该参数来执行此操作:

collection.html collection.html

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

index.html 的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>

You can achieve smooth scrolling using html only 您可以仅使用html来实现平滑滚动

your page contains div like 您的页面包含div之类的

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

You have to scroll to this div using 您必须使用滚动到该div

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

and simply use below code in your css 并简单地在CSS中使用以下代码

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

</style>

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

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