重新加载页面而不向上滚动
Reload page without scrolling up
我通过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');
}
解决方案:
在AJAX success
中添加/调整以下内容:
window.location.hash = "#sp" + $(window).scrollTop();;
window.location.reload(true);
然后在您的document ready
或onload
:中
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中的一个子部分,该解决方案将适用于您。
相关文章:
- 如何做javascript连续滚动-自动加载
- 数据表 AJAX 筛选器重新加载数据
- 等到无限滚动完成加载 - Javascript
- 在用户滚动时加载单个页面网站的不同部分
- 页面滚动时加载角度视图和控制器太慢
- 为什么无限滚动总是加载相同的图像
- jQuery创建无限滚动的加载更多按钮
- 无限ajax滚动未加载javascript
- 实现延迟在滚动上加载未知大小的图像并最佳定位的图像库
- 如何在新加载的页面上执行(下拉)操作
- 根据上一个选项卡的选择器重新加载选项卡
- 每次向上滚动重新加载数据
- 滚动时加载更多 滚动速度时一次工作两次
- 如何在滚动时加载更多数据
- jQuery 无限滚动的加载过早触发
- 获得“中止,因为不接受 0”并使用反应热加载器重新加载整页
- jQuery在页面底部滚动时加载更多内容
- 咕噜咕噜的手表:实时加载重新加载落后 1 步....
- 使用滚动重新加载 Jqgrid 时出现问题 - 重复的行数据并缺少最后一页
- 如何检测响应滚动触发器加载的新内容?