我在尝试以 ajax 成功方式将页面滚动到底部时遇到问题。我正在设置 window.location.href
因为我需要删除 url 中的哈希标签,然后我想将页面滚动到底部。但页面加载后页面仍然位于顶部。下面是我的代码。
我知道在ajax之外重新加载页面后可以编写滚动到底部。但是这种滚动到底部的特殊要求并不总是需要的,它基于某个按钮点击,其中已经编写了ajax。
$.ajax({
url: updatedUrl,
dataType: 'json',
type: 'post',
data: 'id=' + id,
complete: function() {},
success: function(data) {
window.location.href = window.location.href.split('#')[0];
$('.overlay').hide();
var $target = $('html,body');
$target.animate({scrollTop: $target.height()}, 1000);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
这里可能存在什么问题?如何删除哈希标签并将页面滚动到底部?
最佳答案
当你这样做时window.location.href
这将使用新的 URL 重新加载页面,该行旁边的行将不会被执行。
如果您想在不加载页面的情况下更改网址,请替换 window.location.href = window.location.href.split('#'[0];
与 window.history.pushState("string", "Title", window.location.href.split('#')[0]);
这将更改 URL,而无需重新加载
关于javascript - 更改 window.location.href 时不会将页面滚动到底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48945973/