按下特定键后创建一个bootstrap下拉菜单

按下特定键后创建一个bootstrap下拉菜单

下拉菜单 是一组链接或列表,当点击按钮或键盘事件时显示。Bootstrap也提供了一个框架来实现下拉菜单。但是默认的Bootstrap下拉菜单事件只在鼠标点击时触发。

在本文中,我们将看到如何覆盖此默认功能,并在按下特定键后触发bootstrap下拉菜单事件。

让我们逐步实现:

步骤1:添加HTML代码以创建显示下拉菜单的按钮

  • 将bootstrap的最新压缩CSS链接到HTML文档中。
  • 将Bootstrap下拉菜单组件框架添加到HTML代码中。
  • HTML代码可以完美地创建下拉菜单,但默认情况下,下拉事件只发生在鼠标点击时。要在按键时触发此事件,我们必须使用脚本标记添加我们的额外JavaScript代码。

步骤2:添加JavaScript代码以使下拉菜单出现

  • 创建一个变量,并将特定键的键码作为输入。
  • 创建一个名为activateDropdown()的函数,当调用时将显示下拉菜单。在该函数内部,我们选择id为#myDropdown的元素,并切换该div内部所有类(下拉元素)的状态。这里切换状态意味着如果显示则隐藏,如果隐藏则显示。
  • 当按下特定键时调用该函数。

示例: 该示例显示了上述解释的方法。在输出视频中,首先我们输入了键盘上按下的“Enter”键的键码,即13,然后每当我们按下回车键时,下拉事件就会发生。我们可以看到,在下拉事件发生时,鼠标光标也被固定在那里。

<!DOCTYPE html> 
<html> 
<head> 
    <!--Bootstrap Latest Minified Css-->
    <link rel="stylesheet" href= 
"https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"
        integrity= 
"sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
        crossorigin="anonymous"> 
</head> 
  
<body> 
    <!--Bootstrap Framework to create a dropdown-->
    <div class="dropdown"> 
        <button class="btn btn-secondary dropdown-toggle"
            type="button" id="dropdownMenuButton" 
            data-toggle="dropdown" aria-haspopup="true" 
            aria-expanded="false"> 
            Dropdown button 
        </button> 
  
        <div class="dropdown-menu" id="myDropdown" 
            aria-labelledby="dropdownMenuButton"> 
              
            <a class="dropdown-item" href="#"> 
                Action 
            </a> 
            <a class="dropdown-item" href="#"> 
                Another action 
            </a> 
            <a class="dropdown-item" href="#"> 
                Something else here 
            </a> 
        </div> 
    </div> 
    <script> 
        // Create a variable and take the 
        // key-code of the specific key as 
        // an input prompt 
        let keyToShow = prompt("Please enter the " 
            + "key code, After pressing that key " 
            + "dropdown will occur"); 
          
        /* Create a function named activateDropdown() 
        that will show the dropdown menu when called.  
        Inside that function we selected the id named  
        #myDropdown and toggled the state of all the  
        classes (dropdown elements) residing inside  
        that div */ 
        function activateDropdown() { 
            document.getElementById("myDropdown") 
                .classList.toggle("show"); 
        } 
          
        // Call the function when our specific 
        // key is pressed 
        document.addEventListener('keydown', function(event) { 
            if (event.keyCode == keyToShow) { 
                activateDropdown(); 
            } 
        }); 
    </script> 
</body> 
</html>

输出:

按下特定键后创建一个bootstrap下拉菜单

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程