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

时间:2016-03-25 01:24:58

标签: javascript jquery

我通过jQuery通过ajax提交了一些数据,并且在成功时我正在使用

刷新页面
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事件?

2 个答案:

答案 0 :(得分:1)

我们可以使用cookie来完成它。

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

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

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

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

答案 1 :(得分:0)

<强>解决方案:

在你的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中的子部分,该解决方案将适合您。

相关问题