如何限制JavaScript函数中currentline类的增删操作仅在指定屏幕宽度执行
解决方案
你可以通过两种方案实现需求,都能解决移动端JS异常+禁用小屏线条动画的问题:
方案1:JS逻辑拆分+宽度判断(推荐,从根源避免报错)
问题根因是移动端下拉菜单的<a>标签没有data-line属性,原代码取值后调用classList会触发空值报错。修改JS逻辑,只在桌面端+存在data-line属性时执行线条操作:
// 定义桌面端断点,可根据你的实际适配规则调整 const DESKTOP_BREAKPOINT = 768; window.addEventListener('DOMContentLoaded', () => { document.querySelector('#albmenu').addEventListener('click', (event) => { if (event.target.tagName !== 'A') return; // 通用逻辑:切换画廊current类,所有设备都执行 document.querySelector('.current').classList.remove('current'); const galleryName = event.target.getAttribute('data-gallery'); document.querySelector(`.${galleryName}`).classList.add('current'); // 线条动画逻辑:仅桌面端 + 存在data-line属性时执行 const lineName = event.target.getAttribute('data-line'); if (window.innerWidth >= DESKTOP_BREAKPOINT && lineName) { document.querySelector('.currentline')?.classList.remove('currentline'); document.querySelector(`.${lineName}`)?.classList.add('currentline'); } }); });
注:代码里加了可选链操作符?.,避免找不到对应元素时抛出异常
方案2:CSS媒体查询实现(改动最小)
不需要修改JS,直接通过媒体查询在小屏隐藏线条元素,就算JS执行了类操作也不会有视觉效果:
/* 新增媒体查询,断点和你的移动端适配规则保持一致即可 */ @media (max-width: 767px) { .lineparent { display: none; } }
如果只是要禁用动画但保留线条显示,也可以改成覆盖currentline的样式:
@media (max-width: 767px) { .currentline { animation: none; opacity: 0; } }
可选优化:逻辑拆分
如果后续要频繁调整两类逻辑,可以把功能拆成独立函数,维护更清晰:
// 切换画廊 function switchGallery(galleryName) { document.querySelector('.current').classList.remove('current'); document.querySelector(`.${galleryName}`).classList.add('current'); } // 切换线条动画 function switchLine(lineName) { if (!lineName) return; document.querySelector('.currentline')?.classList.remove('currentline'); document.querySelector(`.${lineName}`)?.classList.add('currentline'); } // 事件监听里直接调用 window.addEventListener('DOMContentLoaded', () => { const DESKTOP_BREAKPOINT = 768; document.querySelector('#albmenu').addEventListener('click', (event) => { if (event.target.tagName !== 'A') return; const galleryName = event.target.getAttribute('data-gallery'); const lineName = event.target.getAttribute('data-line'); switchGallery(galleryName); if (window.innerWidth >= DESKTOP_BREAKPOINT) { switchLine(lineName); } }); });
内容的提问来源于stack exchange,提问作者t3rror
相关产品推荐
相关产品推荐

