2017-01-19 14 views
0

私はこの問題をstackoverflowで見ましたが、そこで使用されていたコードは異なっていて、私はそれを本当に理解しませんでした。だから私は別のページからウェブサイトが来ているときにdivにウェブサイトのスクロールをしたい。jQuery自動スクロールID別のページから

$(document).ready(function(){ 
    // Add smooth scrolling to all links 
    $("a").on('click', function(event) { 

    // Make sure this.hash has a value before overriding default behavior 
    if (this.hash !== "") { 
     // Prevent default anchor click behavior 
     event.preventDefault(); 

     // Store hash 
     var hash = this.hash; 

     // Using jQuery's animate() method to add smooth page scroll 
     // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area 
     $('html, body').animate({ 
     scrollTop: $(hash).offset().top -70 
     }, 800, function(){ 

     // Add hash (#) to URL when done scrolling (default click behavior) 
     window.location.hash = hash; 
     }); 
    } // End if 
    }); 
}); 

このコードはホームページで動作し、スムースにスクロールしますが、別のページからクリックすると動作しません。

+0

あなたが見つけた記事へのリンクとは何ですか?これがうまくいかない理由は、クリックすると別のページに移動し、このスクリプトはこのスクリプトを再度レンダリングしますが、すべてがクリックハンドラ内にあるのでスクロールをトリガーしません。 – putvande

答えて

0

これは、ページがロードされる時に、オフセット#someDivトップに体をスクロールします:referrerhttp://www.example.comない場合

$(document).ready(function(){ 

    $('html, body').animate({ 
     scrollTop: $('#someDiv').offset().top - 70 
    }, 800); 

}); 

と、この:

$(document).ready(function(){ 

    if (document.referrer !== "http://www.example.com") { 
     $('html, body').animate({ 
      scrollTop: $('#someDiv').offset().top - 70 
     }, 800); 
    } 

}); 

この他のページから来ているとき:

$(document).ready(function(){ 

    if(document.referrer != '' && document.referrer != location.href){ 
     $('html, body').animate({ 
      scrollTop: $('#someDiv').offset().top - 70 
     }, 800); 
    } 
}); 
関連する問題