我正在使用Ajax请求创建聊天,我试图让消息div滚动到底部没有太多运气。

我将所有内容都包装在这个div中:

#scroll {
    height:400px;
    overflow:scroll;
}

是否有一种方法来保持它滚动到底部默认使用JS?

有办法保持它滚动到ajax请求后的底部吗?


当前回答

像你一样,我正在构建一个聊天应用程序,并希望最近的消息滚动到视图中。这最终对我很有效:

//get the div that contains all the messages
let div = document.getElementById('message-container');

//make the last element (a message) to scroll into view, smoothly!
div.lastElementChild.scrollIntoView({ behavior: 'smooth' });

其他回答

试试下面的代码:

const scrollToBottom = (id) => {
    const element = document.getElementById(id);
    element.scrollTop = element.scrollHeight;
}

你也可以使用Jquery使滚动平滑:

const scrollSmoothlyToBottom = (id) => {
    const element = $(`#${id}`);
    element.animate({
        scrollTop: element.prop("scrollHeight")
    }, 500);
}

下面是演示

下面是它的工作原理:

参考:scrollTop, scrollHeight, clientHeight

如果您的项目针对现代浏览器,您现在可以使用CSS Scroll Snap来控制滚动行为,例如将任何动态生成的元素保持在底部。

.wrapper > div { background-color: white; border-radius: 5px; padding: 5px 10px; text-align: center; font-family: system-ui, sans-serif; } .wrapper { display: flex; padding: 5px; background-color: #ccc; border-radius: 5px; flex-direction: column; gap: 5px; margin: 10px; max-height: 150px; /* Control snap from here */ overflow-y: auto; overscroll-behavior-y: contain; scroll-snap-type: y mandatory; } .wrapper > div:last-child { scroll-snap-align: start; } <div class="wrapper"> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> <div>07</div> <div>08</div> <div>09</div> <div>10</div> </div>

我知道这是一个老问题,但这些解决方案对我都不起作用。我最终使用offset()。顶部得到想要的结果。以下是我在聊天应用程序中轻轻向下滚动屏幕到最后一条消息的方法:

$("#html, body").stop().animate({
     scrollTop: $("#last-message").offset().top
}, 2000);

我希望这能帮助到其他人。

如果你不想依赖scrollHeight,下面的代码可以帮助你:

$('#scroll').scrollTop(1000000);

你可以像这样使用HTML DOM scrollIntoView方法:

var element = document.getElementById("scroll");
element.scrollIntoView();