AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 78857077
Accepted
Andrus
Andrus
Asked: 2024-08-11 05:24:25 +0800 CST2024-08-11 05:24:25 +0800 CST 2024-08-11 05:24:25 +0800 CST

如何通过按键盘键激活引导下拉菜单项

  • 772

Bootstrap 5 导航栏包含下拉菜单。
下拉菜单有带下划线的热键,如a、n、s、e:

<div class="btn-group">
  <button type="button" class="btn btn-danger dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
    Action
  </button>
  <ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#"><u>A</u>ction</a></li>
    <li><a class="dropdown-item" href="#">A<u>n</u>other action</a></li>
    <li><a class="dropdown-item" href="#"><u>S</u>omething else here</a></li>
    <li><hr class="dropdown-divider"></li>
    <li><a class="dropdown-item" href="#">S<u>e</u>parated link</a></li>
  </ul>
</div>

如果按下键盘上的键,如何激活菜单项?例如,如果下拉菜单已打开,则按 A 应该像单击操作菜单项一样。

jsfiddle:https://jsfiddle.net/b6or2s5e/

左箭头和右箭头已经使用

如何使用左右箭头键在 Bootstrap 导航栏中导航

document.addEventListener("DOMContentLoaded", function () {
  document.querySelectorAll('.dropdown').forEach(function (el) {
    el.addEventListener('shown.bs.dropdown', function () {
      document.addEventListener('keydown', function (e) {
        const click = new MouseEvent("click", {
          bubbles: true,
          cancelable: true,
          view: window,
        })
        if (e.key === "ArrowRight") {
          const o = getNextSibling(e.target.closest('.dropdown'), '.dropdown')
          if (!o) {
            document.querySelector('.dropdown-toggle').dispatchEvent(click)
          } else {
            o.querySelector('.Xdropdown-toggle').dispatchEvent(click)
          }
        } else if (e.key === "ArrowLeft") {
          const o = getPrevSibling(e.target.closest('.dropdown'), '.dropdown')
          if (!o) {
            const ar = document.querySelectorAll('.dropdown-toggle')
            ar[ar.length - 1].dispatchEvent(click)
          } else {
            o.querySelector('.dropdown-toggle').dispatchEvent(click)
          }
        }
      }, { once: true })
    })
  })
})

如何添加热键处理?

javascript
  • 1 1 个回答
  • 41 Views

1 个回答

  • Voted
  1. Best Answer
    dale landry
    2024-08-12T01:30:26+08:002024-08-12T01:30:26+08:00

    以下是更新的代码片段,采用动态方法获取下划线元素,并使用forEach循环遍历下划线元素 节点列表,将窗口keydown上的事件与转换为的每个下划线元素的textContent进行比较,然后进行比较。如果匹配,我们将在匹配的元素上运行。 toLowerCase()click()

    如果没有按下 alt 或 ctrl,是否可以删除 switch 语句并针对任意键调用 findUnderlined ?

    我相信您问的是是否可以添加控制键和/或alt键,不能 100% 确定您的问题是否在这里,但您可以根据要使用 keydown 控制的内容添加任何条件。只需将逻辑添加到条件中即可。

    请参阅下面代码片段中的更多注释...

    document.addEventListener("DOMContentLoaded", function() {
      // get drop-down menu
      const dropdownMenu = document.querySelector('.dropdown-menu');
      // get action button
      const action = document.querySelector('#dropdown-btn');
      // get the underlined elements as a nodelist
      const sections = dropdownMenu.querySelectorAll('li u');
      // helper function pass in underlined els and event key
      const setClickForUnderlinedEls = (els, key) => {
        // loop over underlined elements
        els.forEach(sec => {
          // conditional to compare the underlined 
          // elements text to lowercase
          if (key === sec.textContent.toLowerCase()) {
            // simulate a click on element
            sec.click()
          }
        });
      }
      // event click on action button to open dropdown
      action.addEventListener('click', (event) => {
        // window event on keydown to check key
        addEventListener('keydown', (e) => {
          // make sure the dropdown is expanded 
          // using aria-expanded attribute
          if (event.target.ariaExpanded !== 'false') {
            // run helper function to compare the key and
            // the underlined elements textContent
            setClickForUnderlinedEls(sections, e.key);
          }
        });
      })
    });
    

    document.addEventListener("DOMContentLoaded", function() {
      const dropdownMenu = document.querySelector('.dropdown-menu');
      const action = document.querySelector('#dropdown-btn');
      const sections = dropdownMenu.querySelectorAll('li u');
      const setClickForUnderlinedEls = (els, key) => {
        els.forEach(sec => {
          if (key === sec.textContent.toLowerCase()) {
            sec.click()
          }
        });
      }
      action.addEventListener('click', (event) => {
        addEventListener('keydown', (e) => {
          if (event.target.ariaExpanded !== 'false') {
            setClickForUnderlinedEls(sections, e.key);
          }
        });
      })
    });
    #vertical-space,
    #section1,
    #section2,
    #section3,
    #section4,
    #section5{
      height: 100vh;
    }
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    
    <!-- Example single danger button -->
    <div class="btn-group" id="top">
      <!--/ Added the id dropdown-btn for this example /-->
      <button id="dropdown-btn" type="button" class="btn btn-danger dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
        Action
      </button>
      <ul class="dropdown-menu">
        <li><a class="dropdown-item" href="#section1"><u>A</u>ction</a></li>
        <li><a class="dropdown-item" href="#section2">A<u>n</u>other action</a></li>
        <li><a class="dropdown-item" href="#section3"><u>W</u>e have a link</a></li>
        <li><a class="dropdown-item" href="#section4"><u>S</u>omething else here</a></li>
        <li>
          <hr class="dropdown-divider">
        </li>
        <li><a class="dropdown-item" href="#section5">S<u>e</u>parated link</a></li>
      </ul>
    </div>
    <!--/ added purely for example /-->
    <div id="vertical-space">
    </div>
    <div id="section1">
      <p>
        You pressed the <strong>a</strong> button and instantiated a click on the <em>Action</em> button. <a href="#top">Back to top</a>
      </p>
      
    </div>
    <div id="section2">
      <p>
        You pressed the <strong>n</strong> button and instantiated a click on the <em>Another action</em> button. <a href="#top">Back to top</a>
      </p>
    </div>
    <div id="section3">
      <p>
        You pressed the <strong>w</strong> button and instantiated a click on the <em>We have a link</em> button. <a href="#top">Back to top</a>
      </p>
    </div>
    <div id="section4">
      <p>
        You pressed the <strong>s</strong> button and instantiated a click on the <em>Something else here</em> button. <a href="#top">Back to top</a>
      </p>
    </div>
    <div id="section5">
      <p>
        You pressed the <strong>e</strong> button and instantiated a click on the <em>Separate link</em> button. <a href="#top">Back to top</a>
      </p>
    </div>

    • 1

相关问题

  • 合并排序不起作用 - Javascript代码:即使在调试后也无法找到错误

  • select.remove() 方法工作得很奇怪[关闭]

  • useOpenWeather() 中总是出现 401 res -react-open-weather lib [重复]

  • 输入元素没有只读属性,但字段仍然不可编辑[关闭]

  • 如何编辑 D3.js RadialTree 的第一个节点半径?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve