js滚动条保持在最底部的方法,场景:聊天室
方法一、接收消息后,用nextTick() (已测试可行
setTimeout 防止因卡顿没渲染完成,增加容错
nextTick(() => {setTimeout(() => {var container = this.$el.querySelector(".container>div:last-child");container.scrollIntoView();}, 200);});
方法二、定义滚动方法(未测试
<div class="messages" ref="messages" id="chatting">
// 定义滚动到底部的函数
const scrollToBottom = () => {// 获取消息容器的引用const container = document.getElementById("chatting");// 如果 container 不为 null,则执行后续操作if (container) {container.scrollTop = container.scrollHeight;}
};
同上html版本:
<!DOCTYPE html>
<html lang="en">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>将滚动条(scrollbar)保持在最底部的方法</title><style>#chat-box{height: 100px; width: 300px; margin-bottom: 20px; overflow:auto; border: 1px solid #999;}</style><script type="text/javascript">function send() {var chatBox = document.getElementById('chat-box');chatBox.innerHTML = chatBox.innerHTML + 'news_' + new Date().getTime() + '<br />';chatBox.scrollTop = chatBox.scrollHeight; // 【核心代码】} </script>
</head>
<body><div><h3>【滚动条】保持在【最底部】的方法</h3><div><div id="chat-box"></div><input type="button" value="发送消息" onclick="send();"></div></div>
</body>
</html>