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

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

问题描述



完成动画设置后,我将哈希值设置为

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





(这是一个回调函数, id 会在前面分配)。



这很好,允许用户为面板添加书签,也可以让非JavaScript版本工作。 / p>

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



我的问题是:我该如何防止这种情况?即我怎样才能改变窗口的哈希值,但如果哈希存在,不是让浏览器滚动到元素?某些类型的 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 ($ p
$ b $ pre $ code> if(history.pushState){
history.pushState(null,null, '#myhash');
}
else {
location.hash ='#myhash';
}

积分归功于 Lea Verou


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

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

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.

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?

I'm using jQuery 1.4 and the scrollTo plugin.

Many thanks!

Update

Here is the code that changes the panel.

$('#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;

            }
    });
});

解决方案

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

Credit goes to Lea Verou

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

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