带有下拉按钮的响应式导航栏

问题描述 投票:0回答:1

问题:在响应式视图中,当单击任何下拉内容时,下拉按钮不会从菜单图标移动到可见的导航栏。

更详细:在响应式视图中(屏幕宽度低于730px),导航栏变成菜单图标,我希望任何

<a>
或下拉菜单
<button>
在任何下拉项时移动到可见的导航栏被点击。

The issue

代码位于 https://codepen.io/Balazs-Keisz/pen/KKOmgQX

这是处理导航栏的 JavaScript:

    // Function to toggle responsive class for topnav when icon is clicked
    function myFunctionIcon() {
      var x = document.getElementById("myTopnav");
      if (x.className === "topnav") {
        x.className += " responsive";
      } else {
        x.className = "topnav";
      }
    }
    
    // Function to clear all highlights
    function clearAllHighlights() {
      // Remove highlight from all nav items and buttons
      document.querySelectorAll('.nav-item, .dropbtn').forEach(item => {
        item.classList.remove('highlight-menu');
      });
    }
    
    // Function to highlight the clicked button or link
    function highlightButton(clickedElement) {
      clearAllHighlights(); // Clear previous highlights
      clickedElement.classList.add('highlight-menu'); // Highlight the clicked element
      
      
    // If the clicked element is part of a dropdown, ensure only the dropdown button is highlighted
      const dropdownButton = clickedElement.closest('.dropdown')?.querySelector('.dropbtn');
      if (dropdownButton) {
        dropdownButton.classList.add('highlight-menu'); // Highlight only the dropdown button
      }
    }
    
    // Event listeners for nav items and dropbtns
    document.querySelectorAll('.nav-item, .dropbtn').forEach(item => {
      item.addEventListener('click', function(event) {
        highlightButton(this); // Apply highlight
        // Prevent closing the menu when clicking the dropdown button
        if (this.classList.contains('dropbtn')) {
          event.stopPropagation(); // Prevent event from bubbling up
        }
      });
    });
    
    // Event listener for each dropdown content link to close responsive menu
    document.querySelectorAll('.dropdown-content a').forEach(link => {
      link.addEventListener('click', function(event) {
        const dropdownButton = this.closest('.dropdown').querySelector('.dropbtn');
        highlightButton(dropdownButton); // Highlight only the dropdown button
        if (window.innerWidth <= 729) {
          document.getElementById("myTopnav").classList.remove("responsive"); // Close responsive menu
        }
      });
    });
    
    // Event listener for any other responsive <a> links to close the menu
    document.querySelectorAll('.nav-item').forEach(link => {
      link.addEventListener('click', function() {
        if (window.innerWidth <= 729) {
          document.getElementById("myTopnav").classList.remove("responsive"); // Close responsive menu
        }
      });
    });
    
    // Dropdown toggle function for multiple dropdowns
    function toggleDropdown1(dropdownId) {
      var dropdown = document.getElementById(dropdownId);
      dropdown.classList.toggle("show1");
    }
    
    // Function to close all dropdowns
    function closeAllDropdowns() {
      var dropdowns = document.getElementsByClassName("dropdown-content");
      for (var i = 0; i < dropdowns.length; i++) {
        dropdowns[i].classList.remove('show1');
      }
    }

    // Toggle dropdown for the clicked dropdown button
    function toggleDropdown1(dropdownContent) {
      // Check if the clicked dropdown is already open
      var isOpen = dropdownContent.classList.contains('show1');
      
      // Close all dropdowns
      closeAllDropdowns();

      // If the clicked dropdown was not open, open it
      if (!isOpen) {
        dropdownContent.classList.add('show1');
      }
    }

    // Add event listeners for each dropdown button
    document.querySelectorAll('.dropbtn').forEach(button => {
      button.addEventListener('click', function(event) {
        // Prevent closing on the same dropdown click
        event.stopPropagation();

        // Get the corresponding dropdown content
        var dropdownContent = this.nextElementSibling;

        // Toggle the dropdown
        toggleDropdown1(dropdownContent);
      });
    });

    // Close the dropdown if the user clicks outside of any dropdown
    window.addEventListener('click', function(event) {
      if (!event.target.matches('.dropbtn') && !event.target.matches('.dropbtn i')) {
        closeAllDropdowns();
      }
    });

    // Attach event listeners to all <a> and <button> elements for highlighting
    document.querySelectorAll('.nav-item, .dropbtn').forEach(item => {
      item.addEventListener('click', function() {
        highlightButton(this); // Highlight the clicked element
      });
    });
javascript html css responsive-design dropdown
1个回答
0
投票

问题出在这部分

// Event listener for each dropdown content link to close responsive menu
document.querySelectorAll('.dropdown-content a').forEach(link => {
    link.addEventListener('click', function (event) {
        const dropdownButton = this.closest('.dropdown').querySelector('.dropbtn');

您选择了错误的商品

.querySelector('.dropbtn');

这是相关下拉列表的子项。如果孩子的父母被隐藏,则无法显示孩子。因此,要解决此问题,请删除最后一个

.querySelector('.dropbtn')
,然后就可以开始了。

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href='https://fonts.googleapis.com/css?family=Noto Serif' rel='stylesheet'>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
        html {
            font-size: 17px;
            /* Base size */
        }

        body {
            font-family: 'Noto Serif';
            background-color: #eae6e0;
            padding: 0 0 50px 0;
        }

        /* Add a black background color to the top navigation */
        .topnav {
            background-color: #404857;
            overflow: hidden;
            display: flex;
            /* Use flexbox for alignment */
            justify-content: center;
            /* Distribute buttons evenly */
        }

        /* Style the links inside the navigation bar */
        .topnav a {
            float: left;
            display: block;
            color: #f2f2f2;
            text-align: center;
            padding: 14px 16px;
            text-decoration: none;
        }

        .topnav .search-container {
            float: right;
            display: none;
        }

        .topnav .search-container input[type=text] {
            padding: 6px;
            margin-top: 8px;
            border: none;
        }

        .topnav .search-container button {
            float: right;
            padding: 6px 10px;
            margin-top: 8px;
            margin-right: 16px;
            background: #ddd;
            border: none;
            cursor: pointer;
        }

        /* Hide the link that should open and close the topnav on small screens */
        .topnav .icon {
            display: none;
        }

        /* Dropdown container - needed to position the dropdown content */
        .dropdown {
            float: left;
            overflow: hidden;
        }

        /* Style the dropdown button to fit inside the topnav */
        .dropbtn {
            border: none;
            outline: none;
            color: white;
            padding: 14px 16px;
            background-color: #404857;
            font-family: inherit;
            font-size: 1rem;
            margin: 0;
        }

        /* Style the dropdown content (hidden by default) */
        .dropdown-content {
            display: none;
            position: absolute;
            background-color: #f9f9f9;
            min-width: 160px;
            box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
            z-index: 1;
        }

        /* Style the links inside the dropdown */
        .dropdown-content a {
            float: none;
            color: black;
            padding: 12px 16px;
            text-decoration: none;
            display: block;
            text-align: left;
        }

        /* Highlight topnav links, dropdown button and search-container on hover */
        .topnav a:hover,
        .dropbtn:hover {
            color: #ffa668;
        }

        /* Add a grey background to dropdown links on hover */
        .dropdown-content a:hover {
            background-color: #ddd;
            color: #0036cf;
        }

        /* Highlight the current page */
        .highlight-menu {
            background-color: #0036cf;
            color: white;
        }

        .dropdown-content.show1 {
            display: block;
        }

        /* When the screen is less than 730 pixels wide, hide all links. Show the link that contains should open and close the topnav (.icon) */
        @media screen and (max-width: 729px) {
            .topnav {
                display: block;
                /* Remove flexbox layout */
                justify-content: initial;
                /* Reset justify content */
            }

            .topnav a,
            .dropdown,
            .dropbtn,
            .dropdown-content {
                display: none;
                /* Hide by default */
            }

            .highlight-menu {
                display: block !important;
                /* Ensure highlighted elements are displayed */
            }

            .topnav .dropbtn.highlight-menu {
                display: block;
            }

            .topnav a.icon {
                float: left;
                display: block;
                /* Show icon to toggle menu */
            }

            .show1 {
                display: block;
                /* Ensure dropdown contents are visible */
            }

            /* The "responsive" class is added to the topnav with JavaScript when the user clicks on the icon. This class makes the topnav look good on small screens (display the links vertically instead of horizontally) */
            @media screen and (max-width: 729px) {
                .topnav.responsive {
                    position: relative;
                }

                .topnav.responsive a {
                    float: none;
                    display: block;
                    text-align: left;
                }

                .topnav.responsive .dropdown,
                .dropbtn {
                    float: none;
                    display: block;
                    width: 100%;
                    text-align: left;
                }

                .topnav.responsive .dropdown-content {
                    position: relative;
                }
            }
        }
    </style>

    <div class="topnav" id="myTopnav">

        <!-- NOTE: ADDDED THIS CODE -->
        <div id="tab1"></div>
        <div id="tab2"></div>
        <div id="tab3"></div>
        <div id="tab4"></div>
        <div id="tab5"></div>
        <!-- NOTE: ADDDED THIS CODE -->

        <!-- The menu icon (mobile view) -->
        <a href="javascript:void(0);" class="icon" onclick="myFunctionIcon()">&#9776;</a>

        <!-- Navigation items (links and buttons) -->
        <div class="dropdown">
            <!-- NOTE: REMOVE CALL IN onclick ', toggleDropdown1('myDropdown2')' -->
            <button onclick="highlightButton(this)" class="dropbtn">Intro
                <i class="fa fa-caret-down"></i>
            </button>
            <div id="myDropdown1" class="dropdown-content">
                <a href="#" onclick="document.getElementById('tab1').click();">Creator's Note</a>
                <a href="#" onclick="document.getElementById('tab2').click();">Fan Note</a>
            </div>
        </div>
        <a href="#cards" id='cards' class="nav-item">Cards</a>

        <div class="dropdown">
            <!-- NOTE: REMOVE CALL IN onclick ', toggleDropdown1('myDropdown2')' -->
            <button onclick="highlightButton(this)" class="dropbtn">Rules
                <i class="fa fa-caret-down"></i>
            </button>
            <div id="myDropdown2" class="dropdown-content">
                <a href="#" onclick="document.getElementById('tab3').click();">Table of Contents</a>
                <a href="#" onclick="document.getElementById('tab4').click();">Diagrams</a>
                <a href="#" onclick="document.getElementById('tab5').click();">Rule Book Viewer</a>
            </div>
        </div>
        <a href="#strategies" id='strategies' class="nav-item">Strategies</a>
        <a href="#resources" id='resources' class="nav-item">Resources</a>
        <a href="#about" id='about' class="nav-item">About</a>
        <a href="#contact" id='contact' class="nav-item">Contact</a>
    </div>
</head>
<script>
    // Function to toggle responsive class for topnav when icon is clicked
    function myFunctionIcon() {
        var x = document.getElementById("myTopnav");
        if (x.className === "topnav") {
            x.className += " responsive";
        } else {
            x.className = "topnav";
        }
    }

    // Function to clear all highlights
    function clearAllHighlights() {
        // Remove highlight from all nav items and buttons
        document.querySelectorAll('.nav-item, .dropbtn').forEach(item => {
            item.classList.remove('highlight-menu');
        });
    }

    // Function to highlight the clicked button or link
    function highlightButton(clickedElement) {
        clearAllHighlights(); // Clear previous highlights
        clickedElement.classList.add('highlight-menu'); // Highlight the clicked element


        // If the clicked element is part of a dropdown, ensure only the dropdown button is highlighted
        const dropdownButton = clickedElement.closest('.dropdown')?.querySelector('.dropbtn');
        if (dropdownButton) {
            dropdownButton.classList.add('highlight-menu'); // Highlight only the dropdown button
        }
    }

    // Event listeners for nav items and dropbtns
    document.querySelectorAll('.nav-item, .dropbtn').forEach(item => {
        item.addEventListener('click', function (event) {
            highlightButton(this); // Apply highlight
            // Prevent closing the menu when clicking the dropdown button
            if (this.classList.contains('dropbtn')) {
                event.stopPropagation(); // Prevent event from bubbling up
            }
        });
    });

    // Event listener for each dropdown content link to close responsive menu
    document.querySelectorAll('.dropdown-content a').forEach(link => {
        link.addEventListener('click', function (event) {
            // NOTE: SELKECSELECT THE .dropdown item, not it's child
            const dropdownButton = this.closest('.dropdown');//.querySelector('.dropbtn');
            highlightButton(dropdownButton); // Highlight only the dropdown button
            if (window.innerWidth <= 729) {
                document.getElementById("myTopnav").classList.remove("responsive"); // Close responsive menu
            }
        });
    });

    // Event listener for any other responsive <a> links to close the menu
    document.querySelectorAll('.nav-item').forEach(link => {
        link.addEventListener('click', function () {
            if (window.innerWidth <= 729) {
                document.getElementById("myTopnav").classList.remove("responsive"); // Close responsive menu
            }
        });
    });

    // Dropdown toggle function for multiple dropdowns
    function toggleDropdown1(dropdownId) {
        var dropdown = document.getElementById(dropdownId);
        dropdown.classList.toggle("show1");
    }

    // Function to close all dropdowns
    function closeAllDropdowns() {
        var dropdowns = document.getElementsByClassName("dropdown-content");
        for (var i = 0; i < dropdowns.length; i++) {
            dropdowns[i].classList.remove('show1');
        }
    }

    // Toggle dropdown for the clicked dropdown button
    function toggleDropdown2(dropdownContent) {
        // Check if the clicked dropdown is already open
        var isOpen = dropdownContent.classList.contains('show1');

        // Close all dropdowns
        closeAllDropdowns();

        // If the clicked dropdown was not open, open it
        if (!isOpen) {
            dropdownContent.classList.add('show1');
        }
    }

    // Add event listeners for each dropdown button
    document.querySelectorAll('.dropbtn').forEach(button => {
        button.addEventListener('click', function (event) {
            // Prevent closing on the same dropdown click
            event.stopPropagation();

            // Get the corresponding dropdown content
            var dropdownContent = this.nextElementSibling;

            // Toggle the dropdown
            toggleDropdown2(dropdownContent);
        });
    });

    // Close the dropdown if the user clicks outside of any dropdown
    window.addEventListener('click', function (event) {
        if (!event.target.matches('.dropbtn') && !event.target.matches('.dropbtn i')) {
            closeAllDropdowns();
        }
    });

    // Attach event listeners to all <a> and <button> elements for highlighting
    document.querySelectorAll('.nav-item, .dropbtn').forEach(item => {
        item.addEventListener('click', function () {
            highlightButton(this); // Highlight the clicked element
        });
    });
</script>
</body>

</html>

© www.soinside.com 2019 - 2024. All rights reserved.