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

如何仅在移动端实现div的切换功能

实现移动端专属的折叠/展开功能

核心思路

通过CSS媒体查询控制不同屏幕下的元素可见性,结合JS判断当前设备尺寸,仅在移动端执行点击切换逻辑。


方案一:适配现有代码快速实现

1. 添加CSS媒体查询

先通过CSS定义不同屏幕的初始状态,确保非移动端时子元素始终可见:

/* 非移动端(屏幕宽度≥768px):强制子元素显示,覆盖JS修改的行内样式 */
#toggle {
  display: block !important;
}

/* 移动端(屏幕宽度<768px):初始隐藏子元素,给主容器添加点击提示 */
@media (max-width: 767px) {
  #toggle {
    display: none;
  }
  .main_div {
    cursor: pointer;
    user-select: none;
  }
}

2. 修改JS函数,仅在移动端生效

通过window.matchMedia检测当前屏幕尺寸,非移动端直接跳过切换逻辑:

function myFunction() {
  // 匹配移动端断点(可根据需求调整宽度值)
  const isMobile = window.matchMedia("(max-width: 767px)").matches;
  if (!isMobile) return;

  const x = document.getElementById("toggle");
  x.style.display = x.style.display === "none" ? "block" : "none";
}

方案二:类切换方式(推荐,更易维护)

直接操作DOM样式不够灵活,改用添加/移除类的方式,便于后续扩展:

1. 调整CSS代码

/* 默认非移动端:子元素显示 */
#toggle {
  display: block;
}

/* 移动端:仅当添加hidden类时才隐藏子元素 */
@media (max-width: 767px) {
  #toggle.hidden {
    display: none;
  }
  .main_div {
    cursor: pointer;
    user-select: none;
  }
}

2. 优化HTML与JS

移除内联事件,改用事件监听,通过类切换控制显示:

<div class="main_div">
  <h3>Section title</h3>
  <div class="row hidden" id="toggle">
    <div class="col-xs-12 col-lg-5 child">content here</div>
    <div class="col-xs-12 col-lg-5 child">content here</div>
    <div class="col-xs-12 col-lg-5 child">content here</div>
    <div class="col-xs-12 col-lg-5 child">content here</div>
  </div>
</div>

<script>
document.querySelector('.main_div').addEventListener('click', function() {
  const isMobile = window.matchMedia("(max-width: 767px)").matches;
  if (!isMobile) return;

  document.getElementById("toggle").classList.toggle('hidden');
});
</script>

说明

  • 断点宽度(767px)可根据你的需求调整,比如对应Bootstrap的移动端断点。
  • 非移动端时,点击主容器不会触发任何操作,子元素始终保持可见。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 06:22:36