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

求助:实现点击下拉菜单选项显示对应div的功能

下拉菜单切换显示对应内容div的实现方案

1. 初始隐藏所有内容区块

先通过CSS把所有.data类的内容div默认隐藏,仅通过active类控制显示:

.data {
    display: none; /* 默认隐藏所有内容区块 */
}
.data.active {
    display: block; /* 显示带有active类的区块 */
}

2. 用JavaScript监听选择事件

给下拉菜单绑定change事件,每次切换选项时,先隐藏所有内容区块,再显示对应id的目标区块:

// 获取下拉菜单元素和所有内容区块
const typeSelect = document.getElementById('type');
const allContent = document.querySelectorAll('.data');

// 监听下拉选择变化
typeSelect.addEventListener('change', function() {
    // 移除所有区块的active类,统一隐藏
    allContent.forEach(item => item.classList.remove('active'));
    // 给当前选中值对应的区块添加active类,显示它
    document.getElementById(this.value).classList.add('active');
});

// 页面加载时默认显示第一个选项的内容
window.onload = function() {
    document.getElementById(typeSelect.value).classList.add('active');
};

完整可运行代码

将CSS和JS整合到你的HTML中,直接即可运行:

<div class="wrapper">
    <div class="menu">
        <select id="type">
            <option value="Gradients">Gradients</option>
            <option value="Custom Color">Custom Color</option>
            <option value="Custom Image/Video">Custom Image/Video</option>
        </select>
    </div>
</div>

<div class="content">
    <div id="Gradients" class="data">
        <h1>gradient</h1>
    </div>
    <div id="Custom Color" class="data">
        <h1>color</h1>
    </div>
    <div id="Custom Image/Video" class="data">
        <h1>image/video</h1>
    </div>
</div>

<style>
.data {
    display: none;
}
.data.active {
    display: block;
}
</style>

<script>
const typeSelect = document.getElementById('type');
const allContent = document.querySelectorAll('.data');

typeSelect.addEventListener('change', function() {
    allContent.forEach(item => item.classList.remove('active'));
    document.getElementById(this.value).classList.add('active');
});

window.onload = () => {
    document.getElementById(typeSelect.value).classList.add('active');
};
</script>

核心说明

  • 下拉菜单的value与内容div的id一一对应,这是实现选项和内容匹配的关键
  • 通过CSS类切换控制显示状态,比直接操作元素样式更易于维护和扩展
  • 页面加载时默认显示第一个选项的内容,避免初始状态空白

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:51:26