2011-12-01 28 views
4

我有以下問題:window.location.hash - 停止重裝鉻

$('.gotoservices').click(function(){ 
    $('html,body').scrollTo($("#services"),1000); 
    window.location.hash = "services"; 
    return false; 
}); 

此代碼的工作,但由於某些原因,scrollTo之前的頁面閃爍。

如果我刪除window.location.hashreturn false;工作,並且頁面不閃爍/閃爍。

我曾嘗試e.preventDefault - 不工作

我努力尋找周圍的任何工作。

乾杯

+0

我想你只需要其中的一個。設置'window.location.hash'也會滾動到該位置。 – Ryan

+0

@minitech在Chrome的情況下不正確 – Pierre

+0

@Pierre:呃... [不,它不是?](http://jsfiddle.net/minitech/TBAce/) – Ryan

回答

0

爲什麼不只是製作一個專門滾動到#services的函數?您正在告訴您的網絡瀏覽器轉到#services,然後滾動到#services。可能與此有衝突。如果你想更新網址有散列,那麼你可能需要

$(window).bind('hashchange', function(e) { 
    e.preventDefault(); 
}); 

所以它不會試圖「去散」。

+0

感謝 - 沒有定位標記叫做#services它的jquery引用層 - 哈希純粹是存儲狀態。 – user1076082

1

在一般意義上,你可以更新HTML5 history的URL沒有瀏覽器重新呈現什麼:

history.pushState(null, null, '#myhash'); 

當然,你可能會希望對舊的瀏覽器回退,你可能會想只有在動畫完成後才能做到這一點。

因此,整合與您的代碼:

$('.gotoservices').click(function(e){ 
    //Prevent default so the browser doesn't try to do anything 
    e.preventDefault(); 
    var $hash = "#services"; 
    $('html,body').scrollTo($($hash), 1000, function() { 
     //If the browser supports HTML5 history, 
     //use that to update the hash in the URL 
     if (history.pushState) { 
      history.pushState(null, null, $hash); 
     } 
     //Else use the old-fashioned method to do the same thing, 
     //albeit with a flicker of content 
     else { 
      location.hash = $hash; 
     } 
    }); 
});