2015-10-05 76 views
2

當我在index.php上,然後按主頁按鈕,它向下滾動到元素。但是,當我不在index.php上並按下相同的按鈕時,我想更改URL位置,然後滾動到該元素。這是我嘗試:jquery更改位置,然後滾動到元素

$('.home').on('click', function (event) { 

    // If location is index.php do this: 
    if (location.href.indexOf("/index.php") > -1) { 

     $('html, body').animate({ 
      scrollTop: $("#anotherelement").offset().top 
     }, 1000); 

     // If location is not index.php do this: 
    } else { 
     window.location = "index.php"; 

     $('html, body').animate({ 
      scrollTop: $("#anotherelement").offset().top 
     }, 1000); 
    } 
}); 

它只是改變了URL,但是當我不在的index.php它不滾動到元素

+0

你需要的時候你改變你加載一個新的頁面位置,以便您的滾動代碼是無用的,因爲使用它(滾動效應)對DOM已準備就緒功能 – slashsharp

+1

你正在從「上一頁」的頁面 – Saar

回答

1

使用散列而不是使用jQuery滾動到一些元件。

  1. 哈希添加到URL http://www.myurl.com/index.php#anotherelement
  2. 與要在頁面加載滾動頁面相同的ID(anotherelement在這個例子中)添加的元素。
+1

雅這是正確的,但沒有任何動畫。這可以在新加載的頁面上使用'hashchange'事件來處理,但顯然這符合OP需求:) –

0

請更改您的代碼

$('.home').on('click', function (event) { 
    if (location.href.indexOf("/index.php") > -1) { 
     $('html, body').animate({ 
      scrollTop: $("#anotherelement").offset().top 
     }, 1000); 

    } else { 
     window.location = "index.php#anotherelement"; 
    } 
});