如何在不跳文档的情况下更新window.location.hash?
我在我的网站上设置了一个滑动面板。
完成动画制作后,我像这样设置哈希
function() {   window.location.hash = id;
}
(这是一个回调,并且在id前面已分配)。
这很好用,可以使用户在面板上添加书签,也可以使非JavaScript版本正常工作。
但是,当我更新哈希时,浏览器跳到该位置。我想这是预期的行为。
我的问题是:如何预防这种情况?即如何更改窗口的哈希值,但是如果哈希值存在,浏览器
滚动到该元素?某种event.preventDefault()东西吗?
我正在使用jQuery 1.4和scrollTo插件。
非常感谢!
回答:
这是更改面板的代码。
$('#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,而在旧浏览器上进行回退:
if(history.pushState) {    history.pushState(null, null, '#myhash');
}
else {
    location.hash = '#myhash';
}
以上是 如何在不跳文档的情况下更新window.location.hash? 的全部内容, 来源链接: utcz.com/qa/399198.html
