聊天窗口问题

我现在写一个聊天窗口,最后一行总是会被输入框挡住,怎么让滚动条滚到最下面的同时,同时让最后输入(或者是最后显示的历史消息永远在输入框之上,这样我们才能看得见所有内容)图片描述

阅读 2.4k
3 个回答

假设你的输入框是这样写的:

<div class=input>
    <input/>
</div>

相应的样式是这样的:

.input {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 30px;
}

可以改成这样:

首先是DOM:

<div class=input-wrapper>
    <div class=input>
        <input/>
    </div>
</div>

其次样式中加一个:

.input-wrapper {
    min-height: 30px;
}

相当于在底部加了一个Placeholder, 如果你要希望永远在上面的话, 那你就要考虑使用单屏应用了, 也就是让整个page的高度和屏幕高度相同, 然后消息列表的滚动只是滚动自身的内容. 如果这样的话就好办了, 直接flex布局就OK:

首先看DOM:

<!DOCTYPE html>
<html>
<body>
<div class=chatroom>
    <div class=messages>
        <div class=message>...</div>
    </div>
    <div class=input>
        <input/>
    </div>
</div>
</body>
</html>

然后是样式:

html, body, .chatroom {
    height: 100%;
    min-height: 100%;
}

.chatroom {
    display: flex;
    flex-direction: column;
}

.messages {
    display: flex;
    overflow: auto;
    flex-direction: column;
    flex: 1;
}

.message {
    display: flex;
    flex-shrink: 0;
}

.input {
    display: flex;
    flex-direction: row;
    height: 30px;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

聊天区域height = calc( 100vh - 输入框height)

Element.scrollIntoViewIfNeeded(opt_center),故名思意,就是在需要的时候将元素滚动到可视区域。

 你可以看看这个 api

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题