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

技术问询:实现心形按钮控制卡片在收藏栏与原位置的双向迁移

解决方案:心形按钮切换卡片收藏状态

步骤1:修改HTML中的点击事件

把心形按钮的onclick事件改为更清晰的函数调用:

<svg xmlns="http://www.w3.org/2000/svg" class="heart" viewBox="0 0 24 24" onclick="toggleFavorite('drag1')">
  <path stroke-linejoin="round" d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z" />
</svg>

步骤2:编写切换收藏状态的JavaScript函数

添加以下代码,实现点击心形按钮时在原始容器和收藏区之间移动卡片,同时保留原有拖拽功能:

function toggleFavorite(cardId) {
  const card = document.getElementById(cardId);
  const originalContainer = document.querySelector('.section_3');
  const favoriteZone = document.querySelector('.dropzone');
  
  // 判断卡片当前所在容器
  if (card.parentElement === originalContainer) {
    // 移至收藏标签页
    favoriteZone.appendChild(card);
    // 标记已收藏:给心形添加红色填充
    card.querySelector('.heart path').setAttribute('fill', '#ef4444');
  } else {
    // 移回原始容器
    originalContainer.appendChild(card);
    // 取消收藏标记:移除填充样式
    card.querySelector('.heart path').removeAttribute('fill');
  }
}

核心说明

  • 通过parentElement判断卡片位置,实现双向切换逻辑
  • 用填充样式直观区分收藏状态,提升用户体验
  • 完全兼容原有拖拽功能:仅移动DOM元素,不修改拖拽相关属性与事件函数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:05:19