Ajax内容加载后滚动到顶部


Scroll to top after Ajax content load

有没有办法让页面在加载内容后自动滚动到顶部(通过Ajax)?

这是我用来显示内容的代码:

$(document).ready(function () {
    var my_layout = $('#container').layout();
    $("a.item_link").click(function () {
        $("#loader").fadeIn();
        feed_url = $(this).attr("href");
        $.ajax({
            type: "POST",
            data: "URL=" + feed_url,
            url: "view.php",
            success: function (msg) {
                $("#view-area").html(msg);
                $("#loader").fadeOut();
            }
        });
        return false;
    });
});

因此,在"查看区域"加载了内容后,我可以让页面自动滚动到顶部吗?

只需使用滚动功能

scrollTo(0);

如果你想要jquery,那么这里有一个很好的平滑示例:)

来自链接:

$('html, body').animate({ scrollTop: 0 }, 0);
//nice and slow :)
$('html, body').animate({ scrollTop: 0 }, 'slow');

把它放在你的代码

...
        success: function (msg) {
            $("#view-area").html(msg);
            $("#loader").fadeOut();
            //Put code here like so
            $('html, body').animate({ scrollTop: 0 }, 0);
        }

您可以执行$(window).scrollTop(0);

所有ajax请求都有一个回调参数,因此请使用scrollTop(0)。查看关于如何使用ajax回调的jQuery文档。

如果没有回调,请尝试绑定事件侦听器:

document.addEventListener(
    "load",
    function(event) {
        event.composedPath().forEach(function(dom) {
            if (dom.classList && dom.classList.value === "classOfLoadedContent") {
                $(".div-to-be-scrolled").scrollTop($(".content").innerHeight());
            }
        });
    },
    true
);