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

标签 javascript jquery

我正在通过 ajax 使用 jQuery 提交一些数据,成功后我将使用

刷新页面
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,滚动并删除co​​okie:

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

关于javascript - 重新加载页面而不向上滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36212683/

相关文章:

javascript - D3JS中的自定义轴函数

javascript - 如何正确实现 HashMap /我是否需要一个

php - 单独项目的下载计数器,但不同语言的下载计数器相同

javascript - 设置秒表定时器的格式

javascript - 如何获取 'Highlight Keyword' 管道来显示不区分大小写的匹配项?

Javascript - 生成控件并附加

javascript - 使用正则表达式限制文本框中的输入

javascript - 将一个 <div> 附加到另一个 <div> 的水平中心

javascript - 如何在 document.ready block 之外触发 jQuery?

jquery - 如何用jquery改变按钮的href