有没有办法禁用一些现代浏览器(如 Chrome 和 Safari)在页面刷新时记住你的滚动位置的行为?
有没有办法禁用一些现代浏览器(如 Chrome 和 Safari)在页面刷新时记住你的滚动位置的行为?
对于支持history.scrollRestoration的浏览器,可以关闭自动滚动行为:
原始回答:{{Original Answer}}
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
$(document).ready(function(){
window.scrollTo(0, 0);
});
如果那不起作用...
$(document).ready(function(){
setTimeout(function(){
window.scrollTo(0, 0);
}, 1);
});
这将把它推到调用栈的底部。
不仅适用于Chrome,我认为这对所有浏览器都很有效。
window.onload = function () {
window.scrollTo(0, 0);
};
在您更新问题后:
我认为最好使用一些cookies或会话存储。
与其希望setTimout最终出现在堆栈底部,我宁愿强制确保我们达到所需的滚动位置。尽管我仍认为这是一种hack方法,但我希望能够绑定到某种浏览器事件。
var scrollToYPos = 100;
var interval = setInterval(checkPos, 0);
function checkPos() {
if ($(window).scrollTop() == scrollToYPos) {
clearInterval(interval);
} else {
window.scrollTo( 0, scrollToYPos );
checkPos();
}
}
我也遇到了同样的问题。这是我想出来的基本解决方案:
// scroll the user to the comments section if we need to
wt = win.scrollTop();
wb = wt + win.height();
// if scroll position is 0, do this (it's a fresh user), otherwise
// the browser is likely to resume the user's scroll position, in
// which case we don't want to do this
yab.loaded().done(function() {
// it seems that browsers (consistently) set the scroll position after
// page load. Accordingly wait a 1/4 second (I haven't tested this to the lowest
// possible timeout) before triggering our logic
setTimeout(function() {
// if the window top is 0, scroll the user, otherwise the browser restored
// the users scroll position (I realize this fails if the users scroll position was 0)
if(wt === 0) {
p = self.container.offset().top;
if(wb != p) {
win.scrollTop(p - th - 20);
}
}
}, 250);
});
yab.loaded
是一个承诺,在窗口加载完成后解决。相当于$(window).load(function(){ // ... });
。 - Skone我认为最简单的方法是欺骗浏览器重新加载页面,并让它认为这是一个新页面。
window.location = window.location
在我测试过的所有浏览器中,它都能够一致地工作。个人建议避免使用onload回调函数,因为它们可能会在加载期间导致不太美观的跳跃。