JavaScript移除属性/样式失效:菜单关闭时内联display样式无法清除
菜单关闭时无法移除内联display样式的修复方案
问题根源
你的代码存在两个关键错误,导致关闭菜单时无法移除内联display样式:
- API调用错误:直接调用元素的
removeProperty方法是无效的,该方法属于元素的style对象,正确写法应为element.style.removeProperty('display')。 - 逻辑顺序错误:无论打开还是关闭菜单,函数末尾都会执行
display='block'的设置,直接覆盖了关闭分支里的移除操作,导致移除无效。
修复后的代码
修改toggleMenu函数,调整逻辑分支并修正API调用:
function toggleMenu() { // set timeout so that the panel has a chance to roll up // before the menu switches states if (menu.classList.contains('open')) { menu.classList.add('closing'); // 修正API调用:使用style对象的removeProperty方法 document.getElementById('tutu').style.removeProperty('display'); document.getElementById('tututu').style.removeProperty('display'); console.log('ZOINK') rollBack = setTimeout(toggleHorizontal, 500); } else { if (menu.classList.contains('closing')) { clearTimeout(rollBack); } else { toggleHorizontal(); } // 仅在打开菜单时设置display:block document.getElementById('tutu').style.display = 'block'; document.getElementById('tututu').style.display = 'block'; } menu.classList.toggle('open'); document.getElementById('toggle').classList.toggle('x'); }
修复说明
- 修正API调用:通过
element.style.removeProperty正确移除内联样式中的display属性。 - 调整逻辑分支:将设置
display:block的代码移至打开菜单的分支内,避免关闭菜单时被重复设置。 - 保留原有超时逻辑,确保菜单切换的动画流程正常执行。
内容的提问来源于stack exchange,提问作者MrJoky
相关产品推荐
相关产品推荐

