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

点击图片后在其下方切换显示/隐藏价格图表的前端实现问题

实现方案

核心调整点

  • 重构DOM结构,将每张图片与对应价格图表绑定在同一个父容器内,保证图表出现在对应图片下方
  • 新增CSS控制显隐状态,默认隐藏图表容器
  • 修正JS逻辑,实现点击切换显隐的toggle效果

完整可运行代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>点击图片显示价格图表</title>
    <style>
        /* 单个商品容器,控制布局 */
        .goods-item {
            width: 300px;
            margin-bottom: 20px;
            cursor: pointer;
        }
        .goods-item img {
            width: 100%;
            display: block;
            border-radius: 4px;
        }
        /* 价格图表默认隐藏 */
        .price-chart {
            display: none;
            margin-top: 10px;
            padding: 15px;
            background: #f5f5f5;
            border-radius: 4px;
        }
        /* 显示状态的类 */
        .price-chart.show {
            display: block;
        }
        /* 模拟图表的占位样式,可替换为真实的图表渲染代码 */
        .chart-placeholder {
            height: 200px;
            background: #fff;
            border: 1px solid #eee;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666;
        }
    </style>
</head>
<body>
    <!-- 第一个商品 -->
    <div class="goods-item" onclick="toggleChart(1)">
        <img src="https://images.unsplash.com/photo-1497215728101-856f4ea42174?ixid=MnwxMjA3fDF8MHxlZGl0b3JpYWwtZmVlZHwxfHx8ZW58MHx8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=900&q=60" alt="商品1">
        <div class="price-chart" id="chart-1">
            <h4>商品1价格走势</h4>
            <div class="chart-placeholder">这里可替换为Echarts/Chart.js等渲染的真实价格图表</div>
        </div>
    </div>

    <!-- 第二个商品 -->
    <div class="goods-item" onclick="toggleChart(2)">
        <img src="def.jpg" alt="商品2">
        <div class="price-chart" id="chart-2">
            <h4>商品2价格走势</h4>
            <div class="chart-placeholder">这里可替换为Echarts/Chart.js等渲染的真实价格图表</div>
        </div>
    </div>

    <!-- 第三个商品 -->
    <div class="goods-item" onclick="toggleChart(3)">
        <img src="efg.jpg" alt="商品3">
        <div class="price-chart" id="chart-3">
            <h4>商品3价格走势</h4>
            <div class="chart-placeholder">这里可替换为Echarts/Chart.js等渲染的真实价格图表</div>
        </div>
    </div>

    <script>
        function toggleChart(id) {
            // 获取对应图表元素
            const chartEl = document.getElementById(`chart-${id}`);
            // 切换显隐类
            chartEl.classList.toggle('show');
        }
    </script>
</body>
</html>

功能说明

  • 点击任意商品图片,会自动切换对应图表的显隐状态,无需额外判断变量
  • 图表容器默认跟随对应图片排列,布局不需要额外定位调整
  • 你可以把.chart-placeholder的内容替换为实际的图表渲染代码即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:24:01