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

如何替换getElementById为getElementsByClassName,实现点击图标显示对应提示?

解决方案

要实现每个加号点击后对应显示左侧提示,核心是把重复的ID改为Class,并让点击事件绑定到当前元素对应的提示框,以下是完整修改后的代码:

修改后的HTML

<br>
<div class="item-group">
  <div class="shopping-cart-add-on" onclick="showAdded(this)" style="height: 28px; width: 28px"></div>
  <div class="notification-text noDisplay">Added!</div>
</div>

<br><br>
<div class="item-group">
  <div class="shopping-cart-add-on" onclick="showAdded(this)" style="height: 28px; width: 28px"></div>
  <div class="notification-text noDisplay">Added!</div>
</div>

<br><br>
<div class="item-group">
  <div class="shopping-cart-add-on" onclick="showAdded(this)" style="height: 28px; width: 28px"></div>
  <div class="notification-text noDisplay">Added!</div>
</div>

修改后的CSS

.shopping-cart-add-on {
  background-image: url("https://upload.wikimedia.org/wikipedia/commons/9/9e/Plus_symbol.svg");
  background-repeat: no-repeat;
  background-size: 29px 29px;
  background-position: center;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, .1);
  border-radius: 24px;
  padding: 8px;
  cursor: pointer;
  position: relative;
  top: -25px;
  left: 124px;
  transition: all .3s;
}

.item-group {
  position: relative;
}

.notification-text {
  position: absolute;
  text-wrap: nowrap;
  animation-name: msgSuccess;
  animation-duration: 1s;
  opacity: 0;
  color: green;
  left: -80px; /* 固定显示在加号左侧 */
  top: 0;
}

.noDisplay {
  display: none;
}

@keyframes msgSuccess {
  50% {
    opacity: 1;
  }
  99% {
    opacity: 0;
  }
  100% {
    opacity: 0;
    display: none;
  }
}

修改后的JS

function showAdded(btn) {
  // 定位当前加号对应的提示文本
  let message = btn.nextElementSibling;

  if (message.classList.contains('noDisplay')) {
    message.classList.remove('noDisplay');
  }

  // 重置动画,确保每次点击都能触发完整的淡入淡出
  message.style.animation = 'none';
  message.offsetHeight; // 强制触发DOM重绘
  message.style.animation = null;
}

关键改动说明

  1. ID改Class:将重复的#notification-text改为.notification-text,解决DOM中ID唯一性限制导致的选择器失效问题。
  2. 绑定当前元素:点击事件传入this,让函数精准定位触发点击的加号,通过nextElementSibling获取同级的对应提示框。
  3. 定位优化:新增.item-group容器并设置position: relative,让提示文本的绝对定位相对于每个加号的容器,保证提示显示在对应位置。
  4. 动画重置:针对当前提示元素单独重置动画逻辑,确保每次点击都能重新播放完整的淡入淡出效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 10:02:37