gif可能不会动,直接看代码
<style>
.chat-window {
width: 300px;
height: 300px;
overflow-y: scroll;
border: 1px solid black;
background-color: lightskyblue;
padding-top: 20px;
/* transform: rotate(180deg); */
/* 2种,要么都旋转180,要么用flex反向,最好是flex(rotate会导致滚动条也反向) */
display: flex;
flex-direction: column-reverse;
/* end */
}
.chat-window::-webkit-scrollbar {
display: none;
}
.message {
background: white;
margin: 0 10px 10px;
border: 1px solid black;
border-radius: 10px;
padding: 5px;
/* transform: rotate(180deg); */
}
.padding{
flex: 1;
}
</style>
<div class="chat-window">
<div class="padding"></div>
<!-- padding元素消息解决不满一屏时,会靠下排放问题 -->
<div class="message">Message 4</div>
<div class="message">Message 3</div>
<div class="message">Message 2</div>
<div class="message">Message 1</div>
</div>
<input type="text" placeholder="输入消息" onkeydown="if(event.keyCode==13){addMessage()}">
<script>
const chatWindow = document.querySelector('.chat-window');
function addMessage(){
const newMessage = document.createElement('div');
newMessage.classList.add('message', 'new-message');
newMessage.textContent = document.querySelector('input').value;
const padding = document.querySelector('.padding');
chatWindow.insertBefore(newMessage, padding.nextSibling); //插入到padding元素之后; padding始终是第一个元素,其他新插入的倒序;(在vue/react中控制新插入到数组前部即可)
chatWindow.scrollTop = 0; // 让上滚动后再新插入消息也能回到底部;
document.querySelector('input').value = '';
}
</script>