jQuery Javascript scrollTop在Chrome上无法正常工作以恢复滚动条位置 [英] jQuery Javascript scrollTop not working as expected on Chrome to restore scrollbar position

查看:48
本文介绍了jQuery Javascript scrollTop在Chrome上无法正常工作以恢复滚动条位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下jQuery Javascript在卸载事件之前保存滚动条位置并再次重新应用:

I'm using the following jQuery Javascript to save the scrollbar position before the unload event and reapply it again:

$(document).ready(function () {
    document.documentElement.scrollTop = $.cookie("scroll") || 0;
});

window.onbeforeunload = function () {
    $.cookie("scroll", document.documentElement.scrollTop, { expires: 7 });
}

基本上我有一系列刷新页面的链接,我希望浏览器恢复滚动条位置。注意我不能在这个实例中使用AJAX。它在Firefox中很有用。在Chrome和Safari中,它仅在刷新浏览器窗口时有效,而不是在单击链接刷新页面时有效。这就好像点击链接没有被识别为onbeforeunload。

Basically I have a series of links that refresh the page and I would like the browser to restore the scrollbar position. Note I cannot use AJAX in this instance. It works a treat in Firefox. In Chrome and Safari however it only works when the browser window is refreshed, and not when the link is clicked to refresh the page. It's as if clicking the link isn't being recognised as onbeforeunload.

我试图修改代码以使用点击事件设置滚动cookie,如下所示没有运气:

I have tried to modify the code to set the scroll cookie using a click event as follows with no luck:

$(document).ready(function () {
    document.documentElement.scrollTop = $.cookie("scroll") || 0;
});

$('a.lockscrollbar').click(function() {
    $.cookie("scroll", document.documentElement.scrollTop, { expires: 7 });
}

FYI我正在使用带有jQuery cookie插件的jQuery 1.4.2。

FYI I'm using jQuery 1.4.2 with the jQuery cookie plugin.

任何想法?

推荐答案

这是一篇较旧的帖子,但我有与Chrome 20相同的问题。使用jQuery 1.7.1这对我有用:

This is an older post but I was having the same issue with Chrome 20. Using jQuery 1.7.1 this worked for me:

$(window).on('load', function(){
    $('html body').scrollTop(0);
});

这篇关于jQuery Javascript scrollTop在Chrome上无法正常工作以恢复滚动条位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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