【问题标题】:Append divs from bottom with scroll - Chat application example使用滚动从底部追加 div - 聊天应用程序示例
【发布时间】: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


    【解决方案1】:

    好的,所以在搞砸了一些 JS 之后,我想通了。我喜欢这种情况发生...

    这是代码笔...

    http://codepen.io/jareko999/pen/yaQmgk

    我创建了一个 setInterval 函数用于滚动到底部。

    var myVar = setInterval(function(){ 
        window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);
    }, .1);
    

    但是,由于此间隔每 0.1 秒运行一次,我需要终止它以滚动上面的 div(如旧聊天消息),但我希望(新 div 进来的)动画完成。因此,我创建了一个 setTimeout 函数来在 200 毫秒时终止 setInterval 函数。

    setTimeout(function(){ 
        clearInterval(myVar);
    }, 200);
    

    【讨论】:

      猜你喜欢
      • 2020-07-19
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多