0
<script type="text/javascript">    
var elementshoku = document.getElementById("1on1shoku");
    var lastHeightshoku = elementshoku.scrollHeight;
    function detectChangeshoku(){
        var currentHeightshoku = elementshoku.scrollHeight;
        if(lastHeightshoku != currentHeightshoku){
    alert("xxx");
    elementshoku.scrollTop = currentHeightshoku;
    lastHeightshoku = currentHeightshoku;
        }
    }
    var mesazhet_shoku = setInterval(detectChangeshoku, 200); 
</script>

我正在聊天,我想在用户写消息时将 div 滚动到底部。我正在使用该功能,但它不起作用。我确实放了这个alert();函数来检查上面的函数是否有效。我尝试了很多方法,但没有一个有效。知道为什么它不起作用吗?

谢谢


编辑:

我看到我的问题不够清楚。我正在聊天,如果有新消息,我希望 div 自动滚动到底部。在这个答案中,据说是这样做的https://stackoverflow.com/a/7666680/1932887但它对我不起作用。任何想法?

4

3 回答 3

2

使用 jQuery:

jqEl.scrollTop(jqEl.scrollHeight());

使用 DOM:

oEl.scrollTop = oEl.scrollHeight;

小提琴

于 2013-08-24T18:55:08.680 回答
1

在渲染之前,您不能请求getElementById("1on1shoku")并阅读它。scrollHeight将第一行放在 onload 中,如下所示:

<script type="text/javascript">
var elementshoku, lastHeightshoku;
window.onload=function() {
    elementshoku = document.getElementById("1on1shoku");
    lastHeightshoku = elementshoku.scrollHeight;
}
function detectChangeshoku(){
    var currentHeightshoku = elementshoku.scrollHeight;
    if(lastHeightshoku != currentHeightshoku){
        elementshoku.scrollTop = currentHeightshoku;
        lastHeightshoku = currentHeightshoku;
    }
}
var mesazhet_shoku = setInterval(detectChangeshoku, 200);
</script>
于 2013-08-24T18:59:18.483 回答
1

尝试使用 jQuery。它可以帮助您的代码更清晰,更易于理解,以供将来维护。通过使用 jQuery,您可以通过以下方式完成:

$(window).load(function() {
    $("html, body").animate({ scrollTop: $("#1on1shoku").scrollTop() }, 1000);
});
于 2013-08-24T19:03:41.370 回答