如何在不跳转文档的情况下更新 window.location.hash? [英] How can I update window.location.hash without jumping the document?

查看:25
本文介绍了如何在不跳转文档的情况下更新 window.location.hash?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的网站上设置了一个滑动面板.

I have a sliding panel set up on my website.

当它完成动画时,我像这样设置哈希

When it finished animating, I set the hash like so

function() {
   window.location.hash = id;
}

(这是一个回调,id 是之前分配的).

(this is a callback, and the id is assigned earlier).

这很好用,允许用户为面板添加书签,并且非 JavaScript 版本也能工作.

This works good, to allow the user to bookmark the panel, and also for the non JavaScript version to work.

但是,当我更新哈希时,浏览器会跳转到该位置.我想这是预期的行为.

However, when I update the hash, the browser jumps to the location. I guess this is expected behaviour.

我的问题是:我怎样才能防止这种情况发生?IE.如何更改窗口的散列值,但如果散列值存在,则让浏览器滚动到元素?某种 event.preventDefault() 之类的东西?

My question is: how can I prevent this? I.e. how can I change the window's hash, but not have the browser scroll to the element if the hash exists? Some sort of event.preventDefault() sort of thing?

我使用的是 jQuery 1.4 和 scrollTo 插件.

I'm using jQuery 1.4 and the scrollTo plugin.

非常感谢!

这是更改面板的代码.

$('#something a').click(function(event) {
    event.preventDefault();
    var link = $(this);
    var id = link[0].hash;

    $('#slider').scrollTo(id, 800, {
        onAfter: function() {

            link.parents('li').siblings().removeClass('active');
            link.parent().addClass('active');
            window.location.hash = id;

            }
    });
});

推荐答案

在现代浏览器上使用历史 API 并回退旧浏览器有一个解决方法:

There is a workaround by using the history API on modern browsers with fallback on old ones:

if(history.pushState) {
    history.pushState(null, null, '#myhash');
}
else {
    location.hash = '#myhash';
}

归功于 Lea Verou

这篇关于如何在不跳转文档的情况下更新 window.location.hash?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆