jQuery在动态加载内容后滚动到错误的偏移量

jQuery scrolls to wrong offset after dynamically loading content

本文关键字:滚动 错误 偏移量 动态 加载 jQuery      更新时间:2023-09-26

由于某些原因,这段代码通常向上/向下滚动到指定的targetDiv的开始处,而不是将页面滚动到比targetDiv已经在的位置更下的位置。

function postData(data, url, divAction, targetDiv) {
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: function(response) {
            if (divAction == 'hide') {
                $(targetDiv).hide();
                $(targetDiv).empty();
            }
            if (divAction == 'refresh') {
                $(targetDiv).html(response);
                $('html, body').animate({
                    scrollTop: '+=' + $(targetDiv).offset().top + 'px'
                }, 'fast');
            }
        },
        error: function() {
            alert('Error! Plese try again.');
        }
    });
    return false;
};

感谢任何建议!

你应该试试这个:

$('html, body').animate({
    scrollTop: $(targetDiv).offset().top
}, 'fast');
<p只要努力,它就会起作用。`>
targetDiv = $('#id1');
$(targetDiv).html("<iframe src='"www.google.com'" />");
$('html, body').animate({scrollTop: '+=' + $(targetDiv).offset().top + 'px'

},"快")的