首页 > 解决方案 > css气泡聊天上滑动画

问题描述

我正在尝试仅使用 CSS 创建聊天动画。到目前为止,我已经尝试创建这个. 我的问题是当他们不该出现时如何隐藏泡沫?

@keyframes slide {
  from {bottom: -20px}
  to {bottom: 0px}
  0%   { opacity: 0; }
  100% { opacity: 1; }
}

另外,我认为这不是创建聊天动画的最佳方法。当聊天时间越来越长时,我还没有想过如何隐藏旧的气泡聊天。有谁知道创建此动画但仅使用 CSS 的最佳方法是什么?

标签: cssanimationcss-animations

解决方案


关键思想是使用一个 flexbox 容器,flex-direction: column-reverse这样消息始终是底部锚定的。这样做你需要以相反的顺序插入整个聊天的标记。

容器::before顶部有一个以渐变为背景的伪元素,因此,当对话滚动时,消息似乎在顶部区域消失了。

消息上的动画可以使用不同的消息来完成animation-delay,并animation-fill-mode: forwards保留最后一个关键帧的值。

*, *::before {
  box-sizing: border-box;
}

.chat {
  display: flex;
  flex-direction: column-reverse;
  height: 12rem;
  overflow: hidden;
  border: 1px #ccc dashed;
  font: .85rem/1.5 Arial;
  color: #313131;
  position: relative;
}

.chat::before {
  content: "";
  position: absolute;
  z-index: 1;
  top: 0;
  height: 40%;
  width: 100%;
  background: linear-gradient(to bottom, white 20%, rgba(255, 255, 255, 0)) repeat-x;
}

.chat p {
  margin: 0;
  padding: 0;
}

.chat__content {
  flex: 0 1 auto;
  padding: 1rem;
  margin: 0 0.5rem;
  background: var(--bgcolor);
  border-radius: var(--radius);
}

.chat__message {
  width: 45%;
  display: flex;
  align-items: flex-end;
  transform-origin: 0 100%;
  padding-top: 0;
  transform: scale(0);
  max-height: 0;
  overflow: hidden;
  animation: message 0.15s ease-out 0s forwards;
  animation-delay: var(--delay);
  --bgcolor: #d8d8d8;
  --radius: 8px 8px 8px 0;
}

.chat__message_B {
  flex-direction: row-reverse;
  text-align: right;
  align-self: flex-end;
  transform-origin: 100% 100%;
  --bgcolor: #d2ecd4;
  --radius: 8px 8px 0 8px;
}

.chat__message::before {
  content: "";
  flex: 0 0 40px;
  aspect-ratio: 1/1;
  background: var(--bgcolor);
  border-radius: 50%;
}

@keyframes message {
  0% {
    max-height: 100vmax;
  }
  80% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
    max-height: 100vmax;
    overflow: visible;
    padding-top: 1rem;
  }
}
<section class="chat">
   
   <div class="chat__message chat__message_B" style="--delay: 18s;">
      <div class="chat__content">
         <p>Thank you.</p>   
      </div>
   </div>

   <div class="chat__message chat__message_A" style="--delay: 13s;">
      <div class="chat__content">
         <p>Mr.Doe, your current balance is $19,606.76</p>   
      </div>
   </div>
   
   <div class="chat__message chat__message_A" style="--delay: 10s;">
      <div class="chat__content">
         <p>Sure, let me check...</p>   
      </div>
   </div>   

   <div class="chat__message chat__message_B" style="--delay: 6s;">
      <div class="chat__content">
         <p>Hi jane, I'm John Doe. <br />
            I need to know my current account balance</p>   
      </div>
   </div>

   <div class="chat__message  chat__message_A" style="--delay: 1s;">
      <div class="chat__content">
         <p>Hello, my name is Jane.<br />
            How can I help you?</p>   
      </div>
   </div>


</section>


推荐阅读