简体   繁体   English

使用javascript将新内容添加到div时自动将div滚动到底部

[英]autoscroll a div to the bottom on adding new content to the div using javascript

I have a div that takes new content as shown from a text area as shown我有一个 div,它从文本区域获取新内容,如图所示

<div style="overflow: auto; overflow-x: hidden; height:296px;" id="container"></div>

when the div fills to the maximum height, I am trying to achieve that the div should show new contents by scrolling down automatically and this is my attempt当 div 填充到最大高度时,我试图通过自动向下滚动来实现 div 应显示新内容,这是我的尝试

for (var i = 0; i < json.length; i++) {
                        ....
                    document.getElementById('container').innerHTML = contents;
                    //this is the code I am trying to use to make it scroll automatically down when new content is added
                    document.getElementById('container').scrollBottom = y;

                } else {
                    alert('Request failed.  Returned status of ' + xhr.status);

contents in the div is not scrolling down automatically when the div reaches 296px.当 div 达到 296px 时,div 中的内容不会自动向下滚动。 Please what could be wrong?请问可能有什么问题?

I was able to solve my problem using this我能够用这个解决我的问题

$("#container").scrollTop($("#container")[0].scrollHeight); $("#container").scrollTop($("#container")[0].scrollHeight);

the above replaced this:以上取代了这个:

document.getElementById('container').scrollBottom = y; document.getElementById('container').scrollBottom = y;

And my problem is solved.我的问题解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM