我正在通过 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,滚动并删除cookie:
var lastScrollTop = $.cookie('last-scroll-top');
if (lastScrollTop) {
$(window).scrollTop(lastScrollTop);
$.removeCookie('last-scroll-top');
}
关于javascript - 重新加载页面而不向上滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36212683/