You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bootstrap垂直Tabs实现鼠标悬停切换内容的需求及问题

Bootstrap垂直标签页实现鼠标悬停切换内容

你的现有代码仅处理了ul的open类切换,未实现标签内容的核心切换逻辑。要实现鼠标悬停切换标签页内容,需监听导航链接的mouseover事件,触发Bootstrap标签页的切换机制。

解决方案代码

替换你现有的jQuery代码为以下内容:

// 监听所有导航链接的鼠标悬停事件
$('.nav-tabs-dropdown .nav-link').on('mouseover', function(e) {
  // 阻止默认跳转行为
  e.preventDefault();
  
  // 使用Bootstrap官方Tab API完成切换
  const tabInstance = bootstrap.Tab.getOrCreateInstance(this);
  tabInstance.show();
});

代码说明

  1. 绑定mouseover事件:给所有.nav-link绑定鼠标悬停事件,覆盖原有无效逻辑。
  2. 调用Bootstrap Tab API:通过bootstrap.Tab实例化当前导航链接,调用show()方法后,会自动完成:
    • 切换导航链接的active类
    • 切换对应标签内容的show active类
    • 更新aria-selected等无障碍属性,完全符合Bootstrap组件规范

手动实现方案(兼容场景)

如果需要脱离Bootstrap API手动控制状态,可使用以下代码:

$('.nav-tabs-dropdown .nav-link').on('mouseover', function(e) {
  e.preventDefault();
  
  // 更新导航链接的active状态与无障碍属性
  $(this).closest('.nav').find('.nav-link').removeClass('active').attr('aria-selected', 'false');
  $(this).addClass('active').attr('aria-selected', 'true');
  
  // 切换对应标签内容的显示状态
  const targetPane = $(this).data('bs-target');
  $(targetPane).closest('.tab-content').find('.tab-pane').removeClass('show active');
  $(targetPane).addClass('show active');
});

两种方案均可实现鼠标悬停切换标签页的效果,推荐使用第一种基于Bootstrap官方API的方式,稳定性与兼容性更佳。

内容的提问来源于stack exchange,提问作者Gandalf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 02:40:34