javascript
  • jquery
  • html
  • autoscroll
  • 2015-09-17 41 views 0 likes 
    0

    我有這段代碼,當你打開一個鏈接時,它將滾動到該頁面上的特定div。打開鏈接並使用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格。

    我會感謝任何答案。

    回答

    2

    一個簡單的方法來做到這一點只是讓你的鏈接指向一個位置哈希值。

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

    不應該是'about'......沒有「/」嗎? – DelightedD0D

    +1

    @ DelightedD0D這是正確的。此外,我不確定這個解決方案是否可行,因爲如果我沒有弄錯,瀏覽器會自動捕捉到'moreInfo'部分,然後JavaScript有機會平滑滾動。 –

    +0

    是@DelightedD0D,你是對的,我編輯過。我很好奇馬克西米利安的評論,因爲我沒有完全按照原樣進行測試。雖然我現在在生產代碼中的確有類似的東西在爲我工作。 –

    2

    可以通過設置一個GET參數上鍊接的URL,然後讀取參數做到這一點時,下一個頁面加載:

    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> 
    
    相關問題