如何将div滚动到底部?

时间:2022-08-24 23:44:04

Now I have div with following properties:

现在我有以下属性的div:

.chat-history {
    height: 70%;
    overflow: auto;
}

How to scroll it to bottom using js?

如何使用js将其滚动到底部?

3 个解决方案

#1


0  

window.scrollTo(0, document.getElementsByClassName('chat-history')[0].scrollHeight);

I think this will work as you needed. you have to write the class name of the div where you are showing the messages.

我认为这将按你的需要运作。您必须编写显示消息的div的类名。

#2


0  

You can use the scrollTop function in Javascript

您可以在Javascript中使用scrollTop函数

Example:

var obj = document.getElementById("Name of your div");
obj.scrollTop = obj.scrollHeight;

Working fiddle: https://jsfiddle.net/js1vyrxr/3/

工作小提琴:https://jsfiddle.net/js1vyrxr/3/

If you want to use it with jQuery you can use something like this

如果你想在jQuery中使用它,你可以使用这样的东西

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

#3


0  

You can use the javascript scrollTo function

您可以使用javascript scrollTo函数

 window.scrollTo(0, document.body.scrollHeight);

Where 0 is the horizontal scoll and the second parameter is the vertical scroll.

其中0是水平scoll,第二个参数是垂直滚动。

For your example you should get the element and use that element instead of window, like this:

对于您的示例,您应该获取元素并使用该元素而不是窗口,如下所示:

getElementsByClassName('chat-history')

#1


0  

window.scrollTo(0, document.getElementsByClassName('chat-history')[0].scrollHeight);

I think this will work as you needed. you have to write the class name of the div where you are showing the messages.

我认为这将按你的需要运作。您必须编写显示消息的div的类名。

#2


0  

You can use the scrollTop function in Javascript

您可以在Javascript中使用scrollTop函数

Example:

var obj = document.getElementById("Name of your div");
obj.scrollTop = obj.scrollHeight;

Working fiddle: https://jsfiddle.net/js1vyrxr/3/

工作小提琴:https://jsfiddle.net/js1vyrxr/3/

If you want to use it with jQuery you can use something like this

如果你想在jQuery中使用它,你可以使用这样的东西

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

#3


0  

You can use the javascript scrollTo function

您可以使用javascript scrollTo函数

 window.scrollTo(0, document.body.scrollHeight);

Where 0 is the horizontal scoll and the second parameter is the vertical scroll.

其中0是水平scoll,第二个参数是垂直滚动。

For your example you should get the element and use that element instead of window, like this:

对于您的示例,您应该获取元素并使用该元素而不是窗口,如下所示:

getElementsByClassName('chat-history')