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

点击右侧颜色图标时如何修改左侧div背景色与主图URL

解决车型颜色选择模块主图URL切换问题

核心修改步骤

  • 给每个颜色缩略图元素添加自定义数据属性,存储对应颜色的主图URL。示例代码:
    <!-- 给颜色缩略图标签绑定背景色和主图路径 -->
    <div class="color-thumb" data-bg="#e63946" data-img="./images/red-model.jpg">红色</div>
    <div class="color-thumb" data-bg="#457b9d" data-img="./images/blue-model.jpg">蓝色</div>
    
  • 调整JavaScript点击事件逻辑,在原有修改背景色的代码基础上,新增主图URL更新逻辑:
    // 获取所有颜色缩略图、左侧容器、主图元素
    const colorThumbs = document.querySelectorAll('.color-thumb');
    const leftCont = document.querySelector('.leftCont');
    const mainImg = document.getElementById('changeOne');
    
    colorThumbs.forEach(thumb => {
      thumb.addEventListener('click', function() {
        // 保留原有背景色修改逻辑
        const bgColor = this.getAttribute('data-bg');
        leftCont.style.backgroundColor = bgColor;
    
        // 新增:切换主图URL
        const targetImgUrl = this.getAttribute('data-img');
        if (targetImgUrl && mainImg) {
          mainImg.src = targetImgUrl;
          // 可选:添加加载失败提示
          mainImg.onerror = () => console.log(`主图加载失败:${targetImgUrl}`);
        }
      });
    });
    

常见排查点

  • 核对主图元素的id是否准确为changeOne,避免拼写错误(比如大小写、字符遗漏)。
  • 验证data-img中的图片路径是否有效,可直接将路径复制到浏览器地址栏测试能否打开图片。
  • 确保JavaScript代码在DOM加载完成后执行,可将代码放在</body>标签前,或用DOMContentLoaded包裹:
    document.addEventListener('DOMContentLoaded', function() {
      // 这里放上述点击事件逻辑
    });
    
  • 如果颜色缩略图是动态生成的,改用事件委托绑定点击事件,避免事件失效:
    document.addEventListener('click', function(e) {
      if (e.target.classList.contains('color-thumb')) {
        const bgColor = e.target.getAttribute('data-bg');
        leftCont.style.backgroundColor = bgColor;
        const targetImgUrl = e.target.getAttribute('data-img');
        if (targetImgUrl && mainImg) mainImg.src = targetImgUrl;
      }
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 10:12:08