如何将iframe上方Bootstrap导航栏下拉折叠的jQuery脚本转为纯JS
问题解决:Bootstrap导航栏点击iframe不收起的原生JS实现
原有改写的错误点
- 未正确绑定
window的blur事件监听:window.blur()是主动触发窗口模糊事件,而非绑定事件触发时执行的回调函数 document.getElementsByClassName返回的是类数组格式的HTMLCollection集合,不能直接调用仅单个DOM元素支持的classList、属性设置等方法,需要遍历集合内所有元素逐一操作- 混淆了属性读取和设置方法:修改
aria-expanded属性应该使用setAttribute,而非用于读取属性的getAttribute focus是元素方法,必须加括号()才会执行,原改写漏写了执行符号
可用的原生JS代码
window.addEventListener('blur', function() { // 收起所有下拉容器 document.querySelectorAll('.dropdown').forEach(el => el.classList.remove('show')) // 隐藏所有下拉菜单面板 document.querySelectorAll('.dropdown-menu').forEach(el => el.classList.remove('show')) // 重置下拉触发器的无障碍属性并还原焦点 document.querySelectorAll('.dropdown-toggle').forEach(el => { el.setAttribute('aria-expanded', 'false') el.focus() }) })
该代码逻辑和原jQuery脚本完全一致,当点击iframe区域导致主窗口失去焦点时,会自动重置所有Bootstrap下拉菜单的状态,实现点击iframe自动收起导航栏下拉的效果。
内容的提问来源于stack exchange,提问作者fish2
相关产品推荐
相关产品推荐

