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

如何根据下拉选框的值使用JavaScript显示/隐藏div元素?

选项切换显示/隐藏元素的实现方案

现有三个选项(选项0、选项1、选项2),当选中选项1时,需显示videoShowHide元素,隐藏onlineShowHide和handoutShowHide元素。以下是对应的实现代码:

HTML 代码

<div class="col-lg-6 mb-3">
  <label for="type" class="form-label">类型</label>
  <select class="form-select" id="type" name="type">
    <option value="0">在线课程</option>
    <option value="1">视频课程</option>
    <option value="2">讲义资料</option>
  </select>
</div>
<div class="col-lg-6 mb-3" id="onlineShowHide">
  <label for="online" class="form-label">在线课程链接</label>
  <input type="text" class="form-control" id="online" name="online">
</div>
<div class="col-lg-6 mb-3 d-none" id="videoShowHide">
  <label for="video" class="form-label">视频文件</label>
  <input type="file" class="form-control" id="video" name="video">
</div>
<div class="col-lg-6 mb-3 d-none" id="handoutShowHide">
  <label for="handout" class="form-label">讲义文件</label>
  <input type="file" class="form-control" id="handout" name="handout">
</div>

JavaScript 代码

document.getElementById('type').onchange(function() {
  const typeValue = document.getElementById('type').value;
  const onlineEl = document.getElementById('onlineShowHide');
  const handoutEl = document.getElementById('handoutShowHide');
  const videoEl = document.getElementById('videoShowHide');

  if (typeValue === '0') {
    onlineEl.classList.add('d-block');
    onlineEl.classList.remove('d-none');
    handoutEl.classList.add('d-none');
    handoutEl.classList.remove('d-block');
    videoEl.classList.add('d-none');
    videoEl.classList.remove('d-block');
  }
  if (typeValue === '1') {
    onlineEl.classList.add('d-none');
    onlineEl.classList.remove('d-block');
    handoutEl.classList.add('d-none');
    handoutEl.classList.remove('d-block');
    videoEl.classList.add('d-block');
    videoEl.classList.remove('d-none');
  }
  if (typeValue === '2') {
    onlineEl.classList.add('d-none');
    onlineEl.classList.remove('d-block');
    handoutEl.classList.add('d-block');
    handoutEl.classList.remove('d-none');
    videoEl.classList.add('d-none');
    videoEl.classList.remove('d-block');
  }
})

注:原代码仅添加显示/隐藏类未移除相反类,可能导致样式冲突,上述代码已修正该问题,确保元素状态切换准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:10:43