2010-10-26 68 views
5

在加載頁面時,我希望在不更改網址的情況下轉至#content轉到錨點而不更改網址

我想我應該能夠使用

window.location.hash = "content"; 
window.location.replace("#content", ""); 

#content仍然存在於URL。

有什麼更好的方法?


編輯:

也試過

window.location.hash = "content"; 
window.location.replace(window.location.toString().replace("#content", "")); 

但這發送到瀏覽器的一個循環。

回答

3

您可以使用該ID找到錨點的垂直位置,然後滾動到該位置。

+0

那麼容易。謝謝! – 2010-10-26 02:51:08

0

這將有一個很好的動畫做到這一點:

<a href="#link">Click to scroll</a> 

<div id="link" style="margin-top: 1000px; height: 300px; background-color: blue; margin-bottom: 1000px"> 
    Click and scroll to this div without changing url! 
</div> 


<script> 
    $('a').on('click', function(e) { 
     // prevent default anchor click behavior 
     e.preventDefault(); 

     // store hash 
     var hash = this.hash; 

     if ($(hash).length) { 
      $('html, body').animate({ 
       scrollTop: $(hash).offset().top 
      }, 300, function() { 
       // Do something fun if you want! 
      }); 
     } 
    }); 
</script> 

Working JSFiddle