CSS 溢出自动滚动:滚动
Automatic scrolling for CSS overflow: scroll
我正在开发一个聊天应用程序,我有一个显示消息的背景。为了不只是有简单的溢出,我将这一行添加到 css: overflow-y: scroll;
这将添加一个滚动条。这一切都很好,但是有没有办法自动滚动到最新消息所在的底部。也可以在JavaScript.
我的 html 代码如下所示:
<article id="chat">
<script src="chat.js"></script>
</article>
每条消息都将采用这种形式并添加到文章中:
"<p class='msg'>" + msg + "</p>"
代码段已更改:
var targetElm = document.querySelector('.boxChild'), // reference to scroll target
button = document.querySelector('button'); // button that triggers the scroll
// bind "click" event to a button
button.addEventListener('click', function(){
targetElm.scrollIntoView()
})
.box {
width: 80%;
border: 2px dashed;
height: 180px;
overflow: auto;
scroll-behavior: smooth; /* <-- for smooth scroll */
}
.boxChild {
margin: 600px 0 300px;
width: 40px;
height: 40px;
background: green;
}
<button>Scroll to element</button>
<div class='box'>
<div class='boxChild'></div>
</div>
我不得不稍微更改 "so hell" 的答案,因为他的答案只适用于一条消息。我给每条消息一个唯一的 ID,然后使用以下命令滚动到该 ID:
document.querySelector("#msgid" + msgId).scrollIntoView();
我正在开发一个聊天应用程序,我有一个显示消息的背景。为了不只是有简单的溢出,我将这一行添加到 css: overflow-y: scroll;
这将添加一个滚动条。这一切都很好,但是有没有办法自动滚动到最新消息所在的底部。也可以在JavaScript.
我的 html 代码如下所示:
<article id="chat">
<script src="chat.js"></script>
</article>
每条消息都将采用这种形式并添加到文章中:
"<p class='msg'>" + msg + "</p>"
代码段已更改:
var targetElm = document.querySelector('.boxChild'), // reference to scroll target
button = document.querySelector('button'); // button that triggers the scroll
// bind "click" event to a button
button.addEventListener('click', function(){
targetElm.scrollIntoView()
})
.box {
width: 80%;
border: 2px dashed;
height: 180px;
overflow: auto;
scroll-behavior: smooth; /* <-- for smooth scroll */
}
.boxChild {
margin: 600px 0 300px;
width: 40px;
height: 40px;
background: green;
}
<button>Scroll to element</button>
<div class='box'>
<div class='boxChild'></div>
</div>
我不得不稍微更改 "so hell" 的答案,因为他的答案只适用于一条消息。我给每条消息一个唯一的 ID,然后使用以下命令滚动到该 ID:
document.querySelector("#msgid" + msgId).scrollIntoView();