window.location.hash - 停止在chrome中重新加载

时间:2011-12-01 18:40:06

标签: jquery hash location reload scrollto

我有以下问题:

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

此代码有效但由于某种原因,页面在scrollTo之前闪烁。

如果我删除window.location.hashreturn false;正常工作且页面不闪烁/闪烁。

我尝试过e.preventDefault - 无效

我很难找到任何解决方法。

干杯

2 个答案:

答案 0 :(得分:2)

从一般意义上讲,您可以使用HTML5 history更新网址,而无需浏览器重新渲染任何内容:

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;
        }
    });
});

答案 1 :(得分:0)

为什么不直接创建一个专门滚动到#services的函数?您告诉Web浏览器转到#services然后滚动到#services。可能与此有冲突。如果您尝试更新网址以获取哈希值,那么您可能需要

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

因此它不会尝试“转到哈希”。

相关问题