当div滚动高度增加时,jquery向下滚动

时间:2014-04-04 06:04:46

标签: jquery html ajax

使用它,

window.setInterval(function () {
    $.post("include/refresh.php", function (respond) {
        var oldheight = $("#chatbox").prop("scrollHeight");
        $("#chatbox").html(respond);
        var newheight = $("#chatbox").prop("scrollHeight");
    })
    if (newheight > oldheight) {
        $("#chatbox").animate({
            scrollTop: $("#chatbox")[0].scrollHeight;
        }, 'slow');
    } else {}
}, 200);
到目前为止它没有工作,从没有运气的4-5小时尝试。我打印了我从滚动高度得到的东西,它返回div的高度而不是滚动高度。来自jquery的scrolltop使用它返回null。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

尝试

将if条件置于$.post成功块

并且时间增加时间至少为1000ms

window.setInterval(function () {
    $.post("include/refresh.php", function (respond) {
        var oldheight = $("#chatbox").prop("scrollHeight");
        $("#chatbox").html(respond);
        var newheight = $("#chatbox").prop("scrollHeight");
        if (newheight > oldheight) {
            $("#chatbox").animate({
                scrollTop: $("#chatbox")[0].scrollHeight;
            }, 'slow');
        } else {}
    });
}, 200);

<小时/> 更好地使用setTimeout

function ReStart() { //create function
    window.setTimeout(function () {
        $.post("include/refresh.php", function (respond) {
            var oldheight = $("#chatbox").prop("scrollHeight");
            $("#chatbox").html(respond);
            var newheight = $("#chatbox").prop("scrollHeight");
            if (newheight > oldheight) {
                $("#chatbox").animate({
                    scrollTop: $("#chatbox")[0].scrollHeight;
                }, 'slow');
            } else {}
            ReStart();//if post request is success than recall this function
        }).fail(function () {
            ReStart();//if post request is fail than recall this function
        });
    }, 200);
}
ReStart(); //call the function