我有一个进行 ajax 调用的表单,成功后,重新加载(同一)页面并使用 URL 哈希/片段跳转到页面底部提交的数据。
window.location.href = "/this/url/#post-10";
window.location.reload();
...
<div id="post-10">...</div>
我注意到,至少在 Chrome 中,之前的滚动位置比我提供的锚链接更受青睐 - 因此页面重新加载,成功跳转到我的
id
锚点,但是一旦页面加载完成,它就会跳转到卷轴在上一页的位置。
这是标准行为吗?解决此问题的最佳方法是简单地使用
onLoad
或类似的东西强制页面位置吗?
window.location.href = "/this/url/#post-10";
将自行工作,无需再次重新加载页面,这将(据我所知)有利于先前的滚动位置。
如果您使用ajax,为什么要重新加载页面?
只需删除线
window.location.reload();
window.location.href = "/this/url/#post-10";
足以将滚动到 post-10
部分。
var targetOffset = $('#post-10').offset().top ;
var scrollElem = scrollableElement('html', 'body');
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
// scroll is complete
location.hash = 'post-10';
});
// Use the first element that is "scrollable" (cross-browser fix?)
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}