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

如何使用CSS或jQuery选择聊天界面同类连续消息组的最后一个元素

CSS 实现(现代浏览器兼容)

目前主流浏览器已支持 :has() 选择器,可直接通过纯CSS匹配连续同class消息组的最后一项:

/* 匹配自己是.msg-you,且下一个兄弟元素不是.msg-you,或是列表最后一个元素的项 */
.msg-you:has(+ :not(.msg-you)),
.msg-you:last-child {
  border-bottom-right-radius: 30px;
}

/* 匹配连续.msg-them组的最后一项 */
.msg-them:has(+ :not(.msg-them)),
.msg-them:last-child {
  border-bottom-left-radius: 30px;
}

/* 原有相邻同身份消息的圆角规则保留即可 */
.msg-you + .msg-you {
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
}
.msg-them + .msg-them {
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
}

你之前写的 :last-of-type 不生效的原因是该选择器是按元素标签匹配,所有消息都是li标签,只会选中整个列表的最后一个li,无法按class分组匹配。


jQuery 兼容实现

如果需要兼容不支持 :has() 的旧版本浏览器,可以用jQuery遍历打标记的方式实现:

  1. 先写分组最后一项的样式类:
.msg-you.last-in-group {
  border-bottom-right-radius: 30px;
}
.msg-them.last-in-group {
  border-bottom-left-radius: 30px;
}
  1. 加JS逻辑遍历标记连续组最后一项:
function markLastChatGroupItem() {
  $('#chatmsgs li').each(function() {
    const $curr = $(this);
    const $next = $curr.next();
    // 下一个元素不存在 或 下一个元素class和当前不一致,说明当前是同组最后一项
    if (!$next.length || $next.attr('class') !== $curr.attr('class')) {
      $curr.addClass('last-in-group');
    } else {
      $curr.removeClass('last-in-group');
    }
  })
}

// 页面初始化时调用一次,每次新增/删除消息后重新调用即可更新标记
markLastChatGroupItem();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:36:03