【问题标题】:window.location.hash - stop reload in chromewindow.location.hash - 停止在 chrome 中重新加载
【发布时间】:2012-01-10 21:42:06
【问题描述】:

我有以下问题:

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

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

如果我删除 window.location.hash 行,return false; 可以正常工作并且页面不会闪烁/闪烁。

我试过e.preventDefault - 不起作用

我正在努力寻找解决办法。

干杯

【问题讨论】:

  • 我认为您只需要其中一个。设置window.location.hash 也会滚动到该位置。
  • @minitech 在 Chrome 的情况下是不正确的
  • @Pierre: 呃...no, it's not?
  • @minitech:我在思考之前打字不好。这在 chrome 中不起作用的用例是当您设置 window.location.hash 然后设置 window.location.reload() 页面时。重新加载页面时,Chrome 似乎优先于 window.location.hash 指向的位置(在 FireFox 中不是这种情况)

标签: jquery hash location reload scrollto


【解决方案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;
        }
    });
});

【讨论】:

    【解决方案2】:

    为什么不创建一个专门滚动到#services 的函数?您告诉您的网络浏览器转到#services,然后滚动到#services。大概和那个有冲突吧。如果您尝试更新 url 以获取哈希,那么您可能需要

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

    这样它就不会尝试“去散列”。

    【讨论】:

    • 谢谢 - 没有称为 #services 的锚标记,它是层的 jquery 引用 - 哈希纯粹是为了存储状态。
    • 这仍然会加载页面。
    猜你喜欢
    • 2012-08-05
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2014-07-21
    相关资源
    最近更新 更多