2015-10-05 78 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"; 
    } 
});