重新加载页面;锚链接被忽略并且先前的滚动位置受到青睐?

问题描述 投票:0回答:2

我有一个进行 ajax 调用的表单,成功后,重新加载(同一)页面并使用 URL 哈希/片段跳转到页面底部提交的数据。

window.location.href = "/this/url/#post-10";
window.location.reload();

...

<div id="post-10">...</div>

我注意到,至少在 Chrome 中,之前的滚动位置比我提供的锚链接更受青睐 - 因此页面重新加载,成功跳转到我的

id
锚点,但是一旦页面加载完成,它就会跳转到卷轴在上一页的位置。

这是标准行为吗?解决此问题的最佳方法是简单地使用

onLoad
或类似的东西强制页面位置吗?

javascript html google-chrome browser
2个回答
2
投票

window.location.href = "/this/url/#post-10";
将自行工作,无需再次重新加载页面,这将(据我所知)有利于先前的滚动位置。


1
投票

如果您使用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 [];
}
© www.soinside.com 2019 - 2024. All rights reserved.