javascript - 更改 window.location.href 时不会将页面滚动到底部

标签 javascript jquery ajax

我在尝试以 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/

相关文章:

javascript - 将新的 <li> 元素添加到 <ul> 问题中

php - 通过 Ajax 和 PHP 强制下载

javascript - 如何在javascript中获取php echo结果

javascript - 为什么它传递 console.log 作为 Observble subscribe() 函数的参数?

javascript - ng-click 不在 Ionic 中触发

asp.net - 如何通过 FORM 从 ASP.Net MVC 堆栈调用存储过程并在 json 中返回它们?

javascript - 通过 $.get 加载外部文件通常不会返回响应,即使响应代码是 200

jquery - 具有转换内容的图像悬停效果

php - 使用jquery将文本文件导入mysql

php - Laravel 5.1 身份验证 - token 不匹配