我有一个滑动面板设置在我的网站上。
当它完成动画时,我将散列设置如下
function() {
window.location.hash = id;
}
(这是一个回调,前面已经分配了id
)。
这很好用,允许用户为面板添加书签,也可以让非JavaScript版本正常工作。
但是,当我更新散列时,浏览器会跳转到该位置。我猜这是意料之中的行为。
我的问题是:我如何防止这种情况发生?也就是说,我怎样才能改变窗口的散列,但是如果散列存在,而不是会让浏览器滚动到元素?某种event.preventDefault()
之类的东西?
我使用的是jQuery 1.4和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;
}
});
});
发布于 2013-02-04 23:44:08
在现代浏览器上使用历史API,并在旧浏览器上回退,可以解决这个问题:
if(history.pushState) {
history.pushState(null, null, '#myhash');
}
else {
location.hash = '#myhash';
}
功劳归于Lea Verou
发布于 2011-03-24 12:57:00
问题是您正在将window.location.hash设置为元素的ID属性。无论是否使用"preventDefault()“,浏览器都会跳转到该元素,这是预期的行为。
解决这个问题的一种方法是在散列前面加上一个任意值,如下所示:
window.location.hash = 'panel-' + id.replace('#', '');
然后,您需要做的就是在页面加载时检查带前缀的散列。作为一个额外的好处,你甚至可以平滑地滚动到它,因为你现在已经控制了散列值…
$(function(){
var h = window.location.hash.replace('panel-', '');
if (h) {
$('#slider').scrollTo(h, 800);
}
});
如果您需要它始终有效(而不仅仅是在初始页面加载时),您可以使用一个函数来监视对散列值的更改,并动态跳转到正确的元素:
var foundHash;
setInterval(function() {
var h = window.location.hash.replace('panel-', '');
if (h && h !== foundHash) {
$('#slider').scrollTo(h, 800);
foundHash = h;
}
}, 100);
发布于 2013-06-14 20:34:09
便宜又讨厌的解决方案..使用丑陋的#!风格。
要设置它,请执行以下操作:
window.location.hash = '#!' + id;
要阅读它:
id = window.location.hash.replace(/^#!/, '');
因为它与页面中的锚点或id不匹配,所以它不会跳转。
https://stackoverflow.com/questions/3870057
复制相似问题