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

AJAX聊天消息展示优化:根据bot布尔值动态添加CSS类

聊天消息按发送方左右对齐实现方案

一、修改JavaScript代码

在生成聊天消息的HTML时,根据AJAX返回的bot布尔值动态添加right类:

$(document).ready(function() {
  function imgMarkup(model) {
    if (model.mediasrc) {
      return `<img class='imgchat' src=../static/${model.mediasrc}.png/>`
    }
    return '';
  }
  setInterval(function() {
    $.ajax({
      type: 'GET',
      url: "/checkview",
      success: function go(response) {
        console.log(response);
        $("#display").empty();
        for (var model of response.models_to_return) {
          // 根据bot状态动态生成类名
          const chatClass = model.bot ? 'chat right' : 'chat';
          const temp = `
    <div class='${chatClass}'>
      <span class='time-left'>${model.datetime}</span>
      <b>${model.user_id}</b>
      <p>${model.room}</p>
      ${imgMarkup(model)}
    </div>`;
          $("#display").append(temp);
        }
      },
      error: function(response) {
        //alert('An error occured')
      }
    });
  }, 1000);
})

二、补充CSS样式

通过flex布局实现消息的左右对齐,同时可添加背景色区分发送方:

/* 给聊天容器设置flex布局,让子消息可以对齐 */
.chatbox {
  display: flex;
  flex-direction: column;
  gap: 1em;
}

.chat {
  border-top: 1px solid #CCC;
  margin-top: 1em;
  border-radius: 2px;
  color: white;
  padding: 1em;
  display: flex;
  flex-direction: column;
  width: fit-content; /* 消息宽度自适应内容 */
  max-width: 70%; /* 限制消息最大宽度,避免过宽 */
}

/* 机器人消息右对齐 */
.chat.right {
  align-self: flex-end;
  background-color: #007bff; /* 可选:添加背景色区分机器人消息 */
}

/* 用户消息左对齐 */
.chat:not(.right) {
  align-self: flex-start;
  background-color: #28a745; /* 可选:添加背景色区分用户消息 */
}

说明

  • 当model.bot为true时,消息容器会自动添加right类,通过align-self: flex-end实现右对齐;
  • 用户消息默认左对齐,无需额外类;
  • 背景色为可选配置,可根据需求调整或移除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 17:01:20