2011-12-01 43 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; 
     } 
    }); 
});