You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在向div容器内追加新div元素时添加过渡动画效果

新消息过渡效果实现方案

完全可以实现,通过CSS动画即可完成,不需要大幅修改原有代码逻辑,具体实现方式如下:


基础样式配置

首先给聊天容器和消息元素添加基础样式:

/* 聊天容器基础样式 */
.chatbox {
  height: 500px; /* 可根据需求调整高度 */
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  padding: 12px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  margin-bottom: 12px;
}

/* 发送的消息基础样式 */
.mytexts {
  padding: 8px 12px;
  margin: 6px 0;
  background: #1677ff;
  color: #ffffff;
  border-radius: 8px;
  max-width: 70%;
  align-self: flex-end; /* 自己发送的消息靠右显示 */
}

可选过渡效果示例

效果1:右侧滑入+淡入

给.mytexts新增动画配置:

.mytexts {
  /* 原有基础样式不变,新增以下内容 */
  opacity: 0;
  transform: translateX(20px);
  animation: slideIn 0.3s ease forwards;
}

@keyframes slideIn {
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

效果2:缩放弹出

替换动画配置即可:

.mytexts {
  /* 原有基础样式不变,新增以下内容 */
  opacity: 0;
  transform: scale(0.8);
  animation: popUp 0.25s ease forwards;
}

@keyframes popUp {
  70% {
    transform: scale(1.05);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

JS逻辑优化

可以在原有发送逻辑中新增自动滚动到底部、清空输入框的代码,优化使用体验:

function send() {
  const chatbox = document.querySelector(".chatbox");
  const input = document.getElementById("text");
  const inputValue = input.value.trim();
  if (!inputValue) return;
  const newtext = document.createElement("div");
  newtext.classList.add("mytexts");
  newtext.innerHTML = inputValue;
  chatbox.appendChild(newtext);
  // 自动滚动到聊天框底部
  chatbox.scrollTop = chatbox.scrollHeight;
  // 清空输入框
  input.value = '';
}

内容的提问来源于stack exchange,提问作者shawbicc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 08:36:04