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

点击加号按钮时将图标右移并在原位置显示自定义内容的实现方案

实现点击按钮右移并显示自定义卡片的方案

下面是一套可直接复用修改的纯前端实现方案:

1. HTML 结构

把加号按钮和学生卡片放在同一容器中,方便定位控制:

<div class="action-container">
  <!-- 加号按钮 -->
  <button class="plus-btn" id="plusBtn">+</button>
  <!-- 学生信息卡片,默认隐藏 -->
  <div class="student-card" id="studentCard">
    <div class="card-header">
      <img src="https://i.sstatic.net/sXeYZ.png" alt="学生头像" class="avatar">
      <div class="student-info">
        <h3>John Doe</h3>
        <p>学号: S12345</p>
      </div>
    </div>
    <div class="card-body">
      <p>班级: 计算机科学2班</p>
      <p>年龄: 20</p>
      <p>邮箱: john@example.com</p>
    </div>
  </div>
</div>

2. CSS 样式

通过相对/绝对定位控制卡片位置,用类实现按钮移动和卡片显示的切换:

/* 容器设为相对定位,作为卡片的定位基准 */
.action-container {
  position: relative;
  width: fit-content;
  margin: 50px;
}

/* 加号按钮基础样式 */
.plus-btn {
  width: 40px;
  height: 40px;
  font-size: 24px;
  border: none;
  border-radius: 50%;
  background-color: #4CAF50;
  color: white;
  cursor: pointer;
  transition: transform 0.3s ease; /* 平滑移动过渡动画 */
}

/* 按钮右移的触发类 */
.plus-btn.shifted {
  transform: translateX(200px); /* 可根据需求调整移动距离 */
}

/* 学生卡片样式,默认隐藏,定位在按钮原位置 */
.student-card {
  position: absolute;
  top: 0;
  left: 0;
  width: 200px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  display: none;
  z-index: 1;
}

/* 卡片显示的触发类 */
.student-card.show {
  display: block;
}

/* 卡片内部样式,可根据你的设计调整 */
.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 10px;
}

.student-info h3 {
  margin: 0;
  font-size: 16px;
}

.student-info p {
  margin: 2px 0;
  font-size: 12px;
  color: #666;
}

.card-body p {
  margin: 4px 0;
  font-size: 14px;
}

3. JavaScript 逻辑

绑定点击事件,切换按钮的移动状态和卡片的显示状态:

const plusBtn = document.getElementById('plusBtn');
const studentCard = document.getElementById('studentCard');

plusBtn.addEventListener('click', function() {
  // 切换按钮的右移类
  this.classList.toggle('shifted');
  // 切换卡片的显示/隐藏状态
  studentCard.classList.toggle('show');
});

关键修改点

  • 调整移动距离:修改.plus-btn.shifted中的translateX数值,即可改变按钮向右移动的长度
  • 替换卡片内容:直接修改.student-card内的HTML代码,换成你自己的学生信息即可
  • 调整动画速度:修改CSS中transition的0.3s参数,可改变按钮移动的动画时长
  • 重复交互逻辑:点击按钮会切换状态——第一次点击按钮右移+显示卡片,第二次点击按钮复位+隐藏卡片

内容的提问来源于stack exchange,提问作者Indra prashad Sharma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 20:30:39