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

如何在div中放置多个span,实现电影分类标签带关闭按钮且代码不冗余?

解决方案

你可以直接用CSS伪元素实现关闭按钮,完全不需要额外新增DOM元素,既不会有冗余代码,也不会撑开原有标签的尺寸:

1. HTML无需修改

只需要在选中的类型标签上增加active类即可,不需要嵌套额外的关闭span,示例:

<!-- 选中的标签加active类 -->
<span class="active">action</span>
<!-- 未选中的标签不需要任何修改 -->
<span>adventure</span>

2. 修改CSS样式

.genres span{
    color: rgba(0, 0, 0, 0.87);
    display: inline-flex;
    align-items: center;
    text-transform: capitalize;
    cursor: pointer;
    background-color: #fff;
    line-height: 1.2;
    border-radius: 10px;
    /* 右侧预留关闭按钮的空间 */
    padding: 10px 30px 10px 10px;
    font-size: 0.850rem;
    margin: 2px;
    font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    /* 开启相对定位作为关闭按钮的定位父级 */
    position: relative;
}

/* 选中状态的标签样式,可按需调整 */
.genres span.active {
    background-color: #f5f5f5;
}

/* 用伪元素生成关闭按钮,仅选中状态显示 */
.genres span.active::after {
    content: 'x';
    position: absolute;
    right: 4px;
    top: 50%;
    transform: translateY(-50%);
    width: 22px;
    height: 22px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    font-size: 0.8rem;
    color: #3f51b5;
    background-color: rgba(172, 157, 157, 0.7);
}

方案优势

  • 零冗余代码:不需要新增任何额外的DOM节点,原有HTML结构完全不用改动
  • 不会撑开标签尺寸:关闭按钮用绝对定位放置,不会影响原有标签的宽高
  • 逻辑更简洁:后续交互只需要控制标签的active类增减即可,不需要额外操作关闭按钮节点

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:06:04