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

如何用HTML&CSS在产品图片上添加可点击变红的心愿单心形按钮

实现产品图片的心愿单心形按钮

修改后的HTML结构

给图片添加容器来定位心形按钮,新增心愿单按钮元素:

<div class="product">
  <div class="product-img-container">
    <img src="/img/place-holder.png">
    <button class="wishlist-btn" aria-label="加入心愿单">
      <span class="heart-icon">♥</span>
    </button>
  </div>
  <div class="product-text">
    <h4><a href="/Product.html">Produkt</a></h4>
    <h4>199&nbsp;SEK</h4>
  </div>
</div>

更新后的CSS样式

设置容器相对定位,按钮绝对定位在图片右上角,添加默认和激活状态的样式:

.products .product{
  margin: 2em 0;
  width: 300px;
  height: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.product-img-container {
  position: relative;
  width: 100%;
  height: 100%;
  margin-bottom: 1em;
}

.product img{
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.wishlist-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  background: transparent;
  border: none;
  font-size: 24px;
  color: #ccc;
  cursor: pointer;
  padding: 5px;
  transition: color 0.2s ease;
}

.wishlist-btn.active .heart-icon {
  color: #ff3b30;
}

.wishlist-btn:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(255, 59, 48, 0.5);
}

交互逻辑(JavaScript)

处理按钮点击事件,切换激活状态:

const wishlistButtons = document.querySelectorAll('.wishlist-btn');

wishlistButtons.forEach(btn => {
  btn.addEventListener('click', function() {
    this.classList.toggle('active');
    // 此处可添加后端接口调用,实现心愿单的实际存储逻辑
  });
});

补充说明

  • 使用<button>元素确保可访问性,aria-label为屏幕阅读器提供按钮功能说明
  • 心形图标用纯文本♥,也可替换为Font Awesome图标(需引入对应库)
  • 点击切换active类实现颜色过渡,同时可扩展后端交互完成心愿单功能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:25:17