【发布时间】:2016-10-21 21:37:27
【问题描述】:
我希望从底部追加 div。在某个时刻,垂直滚动应该会启动,这样您就可以查看之前添加的 div。我正在尝试复制一个典型的聊天应用程序以及消息是如何从底部传来的。这是codepen...
http://codepen.io/jareko999/pen/yaQmgk
在我输入代码之前,我将解释一下我迄今为止尝试过的几种解决方法。笔目前的容器绝对定位为底部为 0。问题是,一个痛苦的问题是,一旦高度超过视口的高度,它就不会滚动。这是绝对定位解决方法的问题。
我尝试过的另一种解决方法是将高度设置为 100vh 并使用 justify-content flex-end 显示 flex,以便列从底部开始。这样做的问题是滚动总是从顶部开始。我相信解决方案是我创建的滚动功能,每次添加新 div 时都会滚动到底部。这会是最好的方法吗?这里的关键是我希望能够向上滚动到较旧的 div,但让较新的 div 从底部开始。想想一个典型的聊天应用程序,如 slack 或消息或类似的。
HTML
<button onclick="myFunction()">Hey here's a box</button>
<div id="container">
</div>
CSS
body {
margin: 0;
width: 100%;
}
button {
position: fixed;
z-index: 10;
}
#container {
position: absolute;
bottom: 0;
width: 100%;
}
#box {
width: 100%;
background: tomato;
opacity: 0;
height: 100px;
transition: .2s;
}
#box:last-child {
opacity: 1;
height: 0;
animation: .2s height linear forwards;
}
@keyframes height {
to {
height: 100px;
}
}
#box:nth-last-child(2) {
opacity: .8;
}
#box:nth-last-child(3) {
opacity: .6;
}
#box:nth-last-child(4) {
opacity: .4;
}
#box:nth-last-child(5) {
opacity: .2;
}
JS
function myFunction() {
var box = document.createElement("div");
box.setAttribute("id", "box");
var container = document.getElementById('container');
container.appendChild(box);
// window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);
}
有没有比我创建的滚动到底部的功能更好的解决方案?非常感激。
【问题讨论】:
标签: javascript css scroll append chat