如何创建像 Facebook Messenger 这样的聊天气泡

新手上路,请多包涵

在此处输入图像描述

我将如何创建这样的聊天气泡。更具体地说,如何将一种类型的用户的两条或更多条连续消息作为一个整体分组到一个气泡中。例如对于发件人 - 第一条消息的右下边框为 0,中间的消息的右上、下边框为 0 边框半径,最后一条消息的右上边框为 0 边框半径。我必须使用 javascript 还是可以使用 css 来完成。

HTML 结构可以是

<ul>
 <li class="him">By Other User</li>
 <li class="me">By this User, first message</li>
 <li class="me">By this User, secondmessage</li>
 <li class="me">By this User, third message</li>
 <li class="me">By this User, fourth message</li>
</ul>

我应该使用什么样的 CSS 类/样式?

原文由 Raj Nandan Sharma 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 648
2 个回答

这是一个相当基本的示例,但它应该解释您需要的所有基础知识。

大多数解决方案位于 + adjacent sibling selector 内。在这种情况下,它用于将不同的边框半径应用于来自同一个人的连续多条消息。

 ul{
  list-style: none;
  margin: 0;
  padding: 0;
}

ul li{
  display:inline-block;
  clear: both;
  padding: 20px;
  border-radius: 30px;
  margin-bottom: 2px;
  font-family: Helvetica, Arial, sans-serif;
}

.him{
  background: #eee;
  float: left;
}

.me{
  float: right;
  background: #0084ff;
  color: #fff;
}

.him + .me{
  border-bottom-right-radius: 5px;
}

.me + .me{
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
}

.me:last-of-type {
  border-bottom-right-radius: 30px;
}
 <ul>
 <li class="him">By Other User</li>
 <li class="me">By this User, first message</li>
 <li class="me">By this User, secondmessage</li>
 <li class="me">By this User, third message</li>
 <li class="me">By this User, fourth message</li>
</ul>

原文由 Serg Chernata 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是一个纯 css 解决方案,但它取决于您在发送组的最后一条消息时检测和应用 chat__bubble--stop 类的能力。不幸的是伪类 :last-of-type 不能使用;正如其他人指出的那样,群组中的最后一条消息不一定是对话的最后一条。它还使用相邻的同级选择器 ( + )。

 .chat {
  list-style-type: none;
  width: 20em;
}

.chat__bubble {
  margin-bottom: 3px;
  padding: 5px 10px;
  clear: both;
  border-radius: 10px 10px 2px 2px ;
}

.chat__bubble--rcvd {
  background: #f2f2f2;
  color: black;
  float: left;
  border-bottom-right-radius: 10px;
}

.chat__bubble--sent {
  background: #0066ff;
  color: white;
  float: right;
  border-bottom-left-radius: 10px;
}

.chat__bubble--sent + .chat__bubble--sent {
  border-top-right-radius: 2px;
}

.chat__bubble--rcvd + .chat__bubble--rcvd {
  border-top-left-radius: 2px;
}

.chat__bubble--stop {
  border-bottom-right-radius: 10px;
  border-bottom-left-radius: 10px;
}
 <ul class="chat">
 <li class="chat__bubble chat__bubble--rcvd chat__bubble--stop">What are you up to?</li>
 <li class="chat__bubble chat__bubble--sent">Not much.</li>
 <li class="chat__bubble chat__bubble--sent">Just writing some CSS.</li>
 <li class="chat__bubble chat__bubble--sent">I just LOVE writing CSS.</li>
 <li class="chat__bubble chat__bubble--sent chat__bubble--stop">Do you?</li>
 <li class="chat__bubble chat__bubble--rcvd">Yeah!</li>
 <li class="chat__bubble chat__bubble--rcvd">It's super fun.</li>
 <li class="chat__bubble chat__bubble--rcvd chat__bubble--stop">... SUPER fun.</li>
</ul>

原文由 metalex9 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题