请求将jQuery脚本转换为原生JavaScript并解析指定HTML代码
将导航折叠按钮的jQuery代码转换为原生JavaScript
嘿,我来帮你把这段导航折叠功能的jQuery代码转成原生JavaScript,先看看你提供的HTML结构:
<button id='etiquette-xs-button' type="button" class='navbar-toggle margin-left-10px' data-toggle="collapse" data-target="#navigation-etiquette-collapse"> <!-- 请将data-target设置为包含navbar-collapse类的div的ID名称,这样主导航菜单就不会同时折叠。#etiquette-xs-button仅用于选中此按钮,以免选中主导航的切换控件。 --> <span class='sr-only'>Toggle navigation</span> <!-- 这里一般会放汉堡菜单的图标元素,比如三个带有icon-bar类的span --> </button> <!-- 对应的折叠目标容器 --> <div id="navigation-etiquette-collapse" class="navbar-collapse collapse"> <!-- 这里是你要折叠/展开的导航菜单内容 --> </div>
先假设你原来的jQuery代码大概是这类折叠功能的常见写法:
// 原jQuery实现示例 $('#etiquette-xs-button').on('click', function() { const target = $(this).data('target'); $(target).toggleClass('in'); // Bootstrap 3用'in'类控制展开状态 });
下面是完全等价的原生JavaScript实现,没有任何jQuery依赖,还兼顾了可访问性:
// 获取折叠按钮元素 const toggleBtn = document.getElementById('etiquette-xs-button'); // 给按钮绑定点击事件 toggleBtn.addEventListener('click', function() { // 获取data-target属性指向的目标容器ID const targetId = this.getAttribute('data-target'); const collapseContainer = document.querySelector(targetId); // 切换折叠状态:Bootstrap 3用'in',Bootstrap 4+用'show',根据你的版本调整 collapseContainer.classList.toggle('in'); // 可选但推荐:更新按钮的aria-expanded属性,适配屏幕阅读器 const isExpanded = this.getAttribute('aria-expanded') === 'true'; this.setAttribute('aria-expanded', !isExpanded); });
注意事项
- 如果你使用的是Bootstrap 4或更高版本,记得把代码里的
'in'换成'show',因为Bootstrap 4调整了折叠组件的类名 - 这段代码完全兼容现代浏览器,包括IE11(如果需要兼容更老的浏览器,可能需要给
classList加polyfill,但现在一般不需要) - 加入
aria-expanded属性的切换是为了符合WCAG可访问性标准,让屏幕阅读器用户能知道按钮的状态
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

