这让我莫名其妙,我担心我可能做了一些非常愚蠢的事情。
我有一个执行ajax调用的表单,如果调用成功,就重新加载(相同的)页面,并使用URL散列/片段跳转到页面底部提交的数据。
window.location.href = "/this/url/#post-10";
window.location.reload();
...
<div id="post-10">...</div>我注意到,至少在Chrome中,以前的滚动位置比我提供的锚点链接更受青睐-因此页面重新加载,成功地跳转到我的id锚点,但一旦页面加载完成,它就会跳到前一页面上滚动的位置。
这是标准行为吗?解决这个问题的最好方法是简单地使用onLoad或类似的东西强制页面定位吗?
发布于 2012-05-18 00:44:02
window.location.href = "/this/url/#post-10";将会自己工作,不需要第二次重新加载页面,这(据我所知)将有利于前一个滚动位置。
发布于 2012-05-18 01:17:06
如果您使用的是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 [];
}https://stackoverflow.com/questions/10639874
复制相似问题