简体   繁体   English

使用Javascript滚动到列表底部

[英]Scroll to bottom of list with Javascript

I have a for loop that produces a list, I'd like the scrollbar to start at the bottom of the list when the page it open, but I can't seem to be able to make it work after seeing all the available solutions. 我有一个for循环,该循环产生一个列表,我希望滚动条在页面打开时从列表的底部开始,但是在看到所有可用的解决方案之后,我似乎无法使其工作。 Here is my code: 这是我的代码:

HTML: HTML:

<div class="js-conversation" id="msg-list">
<div class="modal-body-scroller">
<ul class="media-list-conversation">
{% for msg in messages | sort(attribute='timestamp') %}
<li>
...list html...
</l>
{% endfor %}
</ul>
</div>
</div>

Here is the JAVASCRIPT: 这是JAVASCRIPT:

var objDiv = document.getElementById("msg-list");
objDiv.scrollTop = objDiv.scrollHeight;

I have tried moving the id="msg-list" around but it has had not effect anywhere. 我尝试过移动id =“ msg-list”,但是它在任何地方都没有作用。 Any help will be appreciated. 任何帮助将不胜感激。

Add jquery and then scroll to the desired element. 添加jquery,然后滚动到所需的元素。

<script
    src="https://code.jquery.com/jquery-1.12.4.min.js"
    integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
    crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('html,body').animate({
                scrollTop: $(".media-list-conversation").offset().top+$(".media-list-conversation").height()
                },
            'slow');
        })
    </script>

Update: 更新:

I have created an example: https://jsfiddle.net/j1oqv7xf/ . 我创建了一个示例: https : //jsfiddle.net/j1oqv7xf/ It has multiple div elements with dummy text and one desired div with a red border. 它具有多个带有伪文本的div元素和一个带有红色边框的所需div。 When the page finish loading, the page scrolls to the desired div bottom. 页面加载完成后,页面滚动到所需的div底部。

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

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