重新加载页面而不向上滚动

Reload page without scrolling up

本文关键字:滚动 新加载 加载      更新时间:2023-09-26

我通过ajaxjQuery提交了一些数据,成功后我将使用刷新页面

document.location.reload(true);

有什么方法可以防止页面从顶部向后滚动吗。我做了一些研究,似乎有可能愚弄Chrome。我还遇到了以下函数,但不太确定将其放置在何处才能正常工作。

if (window.location.hash) { 
    //bind to scroll function
    $(document).scroll( function() {
        var hash = window.location.hash
        var hashName = hash.substring(1, hash.length);
        var element;
        //if element has this id then scroll to it
        if ($(hash).length != 0) {
            element = $(hash);
        }
        //catch cases of links that use anchor name
        else if ($('a[name="' + hashName + '"]').length != 0)
        {
            //just use the first one in case there are multiples
            element = $('a[name="' + hashName + '"]:first');
        }
        //if we have a target then go to it
        if (element != undefined) {
            window.scrollTo(0, element.position().top);
        }
        //unbind the scroll event
        $(document).unbind("scroll");
    });
}

由于我正在刷新此页面,在通过单击某个元素提交后,我是否应该以某种方式将其附加到.click事件?

我们可以使用cookie来完成。

在重新加载页面之前,请为scrollTop的最后一个位置添加cookie:

$.cookie('last-scroll-top', $(window).scrollTop());
document.location.reload(true);

当页面重新加载时,我们读取cookie,滚动并删除cookie:

var lastScrollTop = $.cookie('last-scroll-top');
if (lastScrollTop) {
    $(window).scrollTop(lastScrollTop);
    $.removeCookie('last-scroll-top');
}

解决方案:

在AJAX success中添加/调整以下内容:

window.location.hash = "#sp" + $(window).scrollTop();;
window.location.reload(true);

然后在您的document readyonload:中

if (window.location.hash) {
    var hash = window.location.hash;
    var pos = hash.substring(3, hash.length); //3 is used to remove "#sp" from hash name
    if(!isNaN(pos))
        window.scrollTo(0, pos);
    }

免责声明:如果您有正当理由重新加载整个页面,而不仅仅是div中的一个子部分,该解决方案将适用于您。