窗口调整后撤销JS onclick函数:仅700px宽以下点击显示内容
解决移动端内容切换与窗口自适应问题
问题根源
你之前的代码直接修改元素的style.display生成内联样式,而内联样式优先级远高于CSS媒体查询,导致窗口大小调整后,媒体查询的规则无法覆盖内联样式,没法自动隐藏内容。
解决方案
改用CSS类控制显示状态,配合媒体查询和窗口resize监听,既能实现移动端点击切换,又能在窗口大小变化时自动重置状态:
1. HTML结构(简化冗余内联样式)
<button onclick="myFunction()">About</button> <div id="dropdown-content">下拉内容</div> <div id="landing">主内容</div>
2. CSS样式(用类和媒体查询控制显示)
/* 默认状态:隐藏下拉内容,显示主内容 */ #dropdown-content { display: none; } #landing { display: block; } /* 激活类:切换显示状态 */ #dropdown-content.active { display: block; } #landing.hidden { display: none; } /* 屏幕宽度>700px时,强制重置状态,优先级高于类 */ @media only screen and (min-width: 701px) { #dropdown-content, #dropdown-content.active { display: none !important; } #landing, #landing.hidden { display: block !important; } }
3. JavaScript逻辑(仅在移动端执行切换,监听窗口变化)
function myFunction() { const isMobile = window.matchMedia('(max-width: 700px)').matches; if (!isMobile) return; // 非移动端直接返回,不执行切换 const dropdown = document.getElementById('dropdown-content'); const landing = document.getElementById('landing'); // 切换类实现显示/隐藏 dropdown.classList.toggle('active'); landing.classList.toggle('hidden'); } // 监听窗口大小变化,超过700px时自动重置状态 window.addEventListener('resize', () => { const isDesktop = window.matchMedia('(min-width: 701px)').matches; if (isDesktop) { const dropdown = document.getElementById('dropdown-content'); const landing = document.getElementById('landing'); dropdown.classList.remove('active'); landing.classList.remove('hidden'); } });
关键说明
- 用
classList.toggle替代直接修改内联样式,让CSS规则可以正常生效; - 媒体查询中使用
!important确保屏幕变大时,强制覆盖类的样式,自动重置内容状态; - 点击函数里先判断屏幕宽度,非移动端不执行切换逻辑,避免无效操作。
内容的提问来源于stack exchange,提问作者Lucy
相关产品推荐
相关产品推荐

