Показывать только активное содержимое раскрывающегося меню — несколько кнопок раскрывающегося списка на панели навигации

У меня есть панель навигации с несколькими кнопками, которые при нажатии отображают раскрывающееся меню. Что происходит: когда я нажимаю кнопку, отображается раскрывающееся меню, затем, когда я нажимаю за пределами меню, оно скрывает активное меню, которое находится справа.

Показывать только активное содержимое раскрывающегося меню — несколько кнопок раскрывающегося списка на панели навигации

       function myFunction(num) {
          document.getElementById("myDropdown" + num).classList.toggle("show"); 
       }
       
       window.onclick = function(event) {
          if (!event.target.matches('.dropbtn')) {
             var dropdowns = document.getElementsByClassName("dropdown-content");
             var i;
             for (i = 0; i < dropdowns.length; i++) {
                var openDropdown = dropdowns[i];
                if (openDropdown.classList.contains('show')) {
                   openDropdown.classList.remove('show');
                }
             }
          }
       }
.ul {
  
}
header {
    position: fixed;
    right: 0;
    top: 0;
    left: 0;
    z-index: 100;
    height: 60px;
    box-shadow: 0px 5px 5px -5px rgb(0 0 0 /10%);
    background: #4891c4;;
    color: #ffffff;
    transition: left 300ms;
}

.header-content {
    position: relative;
    top: 0;
    width: 200px;
    height: 60px;
    float: right;
    align-items: center;
    justify-content: center;
}

.header-content, .header-menu {
    display: flex;
    align-items: center;
}

.header-content {
    justify-content: space-between;
    padding: 0rem 1rem;
}

.header-content label:first-child span {
    font-size: 1.3rem;
}

.header-content label {
    cursor: pointer;
}

.arrow_box {
    top: 10px;
    position: relative;
    border: 1px solid #aaa;         /*set border colour here*/
    width: 300px;
    height: auto;
    background-color: #d6eef9;      /*set menu container background color here*/
    border-radius: 3px;
    -webkit-filter: drop-shadow(0 1px 10px rgba(113, 158, 206, 0.8)); /*set shadow colour  and size here*/
    -moz-box-shadow: 0 1px 10px rgba(113, 158, 206, 0.8);
    filter: drop-shadow(0 1px 10px rgba(113, 158, 206, 0.8));
}

.arrow_box:after,
.arrow_box:before {
    bottom: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
}

.arrow_box:after {
    border-color: rgba(255, 255, 255, 0);
    border-bottom-color: #d6eef9;
    border-width: 10px;
    right: 8px;
    margin-right: 0px;
}

.dropdown { 
    display: flex;
    height: 40px;
    width: 40px;
    border-radius: 50%;
    position: relative;
    justify-content: center;
    align-items: center;    
    margin-right: 1rem;
}

.dropdown-content {
    display: none;
    position: absolute;
    min-width: 160px;
    overflow: none;
    z-index: 1;
    right: 0;
    margin-right: 0rem;
    top: calc(100% + 0rem);
}
  
.header-dropdown {
    background-color: #d6eef9; 
}

.header-dropdown ul li:hover {
    background: #d8e2ec;
}
.header-dropdown ul {
    list-style-type: none;
    padding: 0;
    text-align: center;
}
.header-dropdown a {
    text-decoration: none;
    color: var(--menu-color);
    display: block;
    padding: 0.5rem 0rem 0.5rem 1rem;   /* control menu height here */
    text-align: left;       /* control menu text align here center, left or right */
}
.header-dropdown a span {
    min-height: 15px;
    display: inline-flex;
    align-items: center;
    font-size: 1.7rem;
    margin: 0rem 0.5rem 0rem 0.5rem !important;
}
.header-dropdown a span, .header-dropdown a small {
    color: #327091;
}
.header-dropdown a small {
    font-size: 0.95rem;                             /* Sidebar font size */
    font-weight: normal;
    margin: 0rem 1rem 0rem 1rem !important;
    font-family: 'Open Sans', sans-serif;
}

 
.dropbtn {
    border: none;
    cursor: pointer;
}

.show {
    display: block;
}

.notification { 
    display: flex;
    height: 30px;
    width: 30px;
    border-radius: 50%;
    position: relative;
    cursor: pointer;
    color: white;
    padding: 1px;       
    font-size: 1.8rem;
    justify-content: center;
    align-items: center;
}

.badge {
    display: flex;
    position: absolute;
    background: red;
    height: 7px;
    width: 7px;
    justify-content: center;
    align-items: center;
    border-radius: 50%;
    right: -7px;
    top: -7px;
    padding: 8px;
    color: #fff;
    font-size: .8rem;
    font-weight: 500;
}
<link rel = "stylesheet" href = "https://maxst.icons8.com/vue-static/landings/line-awesome/line-awesome/1.3.0/css/line-awesome.min.css">

<header>
<div class = "header-content">
    <div class = "dropdown">
        <a>
          <div onclick = "myFunction(1)" href = "#" class = "notification dropbtn las la-envelope"></div>
          <span onclick = "myFunction(1)" class = "badge dropbtn">4</span>
        </a>
        
        <div id = "myDropdown1" class = "dropdown-content">                 
                <div class = "arrow_box">
                    <div class = "header-dropdown">
                         <ul>
                            <li><a href = ""><small>Message content</small></a></li>
                            <li><a href = ""><small>Message content</small></a></li>
                        </ul>                   
                    </div>
                </div>
            </div>
    </div>
    
    <div class = "dropdown">
        <a>
          <div onclick = "myFunction(2)" href = "#" class = "notification dropbtn las la-bell"></div>
          <span onclick = "myFunction(2)" class = "badge dropbtn">8</span>
        </a>
        
        <div id = "myDropdown2" class = "dropdown-content">                 
            <div class = "arrow_box">
                <div class = "header-dropdown">
                     <ul>
                        <li><a href = ""><span class = "las la-question"><small>FAQ</small></span></a></li>
                        <li><a href = ""><span class = "las la-user"><small>Profile</small></span></a></li>
                        <li><a href = ""><span class = "las la-cog"><small>Settings</small></span></a></li>
                        <li><a href = ""><span class = "las la-sign-out-alt"><small>Log out</small></span></a></li>
                    </ul>                   
                </div>
            </div>
        </div>
    </div>
</div>
</header>

Проблема в том, что когда я нажимаю кнопку, отображается раскрывающееся меню, затем, когда я нажимаю другую кнопку, последнее меню все еще отображается, а не исчезает, это означает, что оно будет отображать два содержимого меню одновременно.

Мне нужно скрыть содержимое последнего меню и показать активное содержимое последнего меню.

Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
1
0
53
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

При открытии меню необходимо удалить класс show из других пунктов меню.

Я изменил ваш myFunction на приведенный ниже код. Если выбранный элемент уже имеет класс show, он будет удален. В противном случае forEach пройдёт по всем пунктам меню и удалит из них класс show.

function myFunction(num) {
  if (document.getElementById("myDropdown" + num).classList.contains('show')) {
    document.getElementById("myDropdown" + num).classList.remove('show');
    return;
  }
  Array.from(document.getElementsByClassName("dropdown-content")).forEach(x => {
    if (x.classList.contains('show'))
      x.classList.remove('show');
  });
  document.getElementById("myDropdown" + num).classList.toggle("show");
}

Рабочий пример.

function myFunction(num) {
  if (document.getElementById("myDropdown" + num).classList.contains('show')) {
    document.getElementById("myDropdown" + num).classList.remove('show');
    return;
  }
  Array.from(document.getElementsByClassName("dropdown-content")).forEach(x => {
    if (x.classList.contains('show'))
      x.classList.remove('show');
  });
  document.getElementById("myDropdown" + num).classList.toggle("show");
}

window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
.ul {}

header {
  position: fixed;
  right: 0;
  top: 0;
  left: 0;
  z-index: 100;
  height: 60px;
  box-shadow: 0px 5px 5px -5px rgb(0 0 0 /10%);
  background: #4891c4;
  ;
  color: #ffffff;
  transition: left 300ms;
}

.header-content {
  position: relative;
  top: 0;
  width: 200px;
  height: 60px;
  float: right;
  align-items: center;
  justify-content: center;
}

.header-content,
.header-menu {
  display: flex;
  align-items: center;
}

.header-content {
  justify-content: space-between;
  padding: 0rem 1rem;
}

.header-content label:first-child span {
  font-size: 1.3rem;
}

.header-content label {
  cursor: pointer;
}

.arrow_box {
  top: 10px;
  position: relative;
  border: 1px solid #aaa;
  /*set border colour here*/
  width: 300px;
  height: auto;
  background-color: #d6eef9;
  /*set menu container background color here*/
  border-radius: 3px;
  -webkit-filter: drop-shadow(0 1px 10px rgba(113, 158, 206, 0.8));
  /*set shadow colour  and size here*/
  -moz-box-shadow: 0 1px 10px rgba(113, 158, 206, 0.8);
  filter: drop-shadow(0 1px 10px rgba(113, 158, 206, 0.8));
}

.arrow_box:after,
.arrow_box:before {
  bottom: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.arrow_box:after {
  border-color: rgba(255, 255, 255, 0);
  border-bottom-color: #d6eef9;
  border-width: 10px;
  right: 8px;
  margin-right: 0px;
}

.dropdown {
  display: flex;
  height: 40px;
  width: 40px;
  border-radius: 50%;
  position: relative;
  justify-content: center;
  align-items: center;
  margin-right: 1rem;
}

.dropdown-content {
  display: none;
  position: absolute;
  min-width: 160px;
  overflow: none;
  z-index: 1;
  right: 0;
  margin-right: 0rem;
  top: calc(100% + 0rem);
}

.header-dropdown {
  background-color: #d6eef9;
}

.header-dropdown ul li:hover {
  background: #d8e2ec;
}

.header-dropdown ul {
  list-style-type: none;
  padding: 0;
  text-align: center;
}

.header-dropdown a {
  text-decoration: none;
  color: var(--menu-color);
  display: block;
  padding: 0.5rem 0rem 0.5rem 1rem;
  /* control menu height here */
  text-align: left;
  /* control menu text align here center, left or right */
}

.header-dropdown a span {
  min-height: 15px;
  display: inline-flex;
  align-items: center;
  font-size: 1.7rem;
  margin: 0rem 0.5rem 0rem 0.5rem !important;
}

.header-dropdown a span,
.header-dropdown a small {
  color: #327091;
}

.header-dropdown a small {
  font-size: 0.95rem;
  /* Sidebar font size */
  font-weight: normal;
  margin: 0rem 1rem 0rem 1rem !important;
  font-family: 'Open Sans', sans-serif;
}

.dropbtn {
  border: none;
  cursor: pointer;
}

.show {
  display: block;
}

.notification {
  display: flex;
  height: 30px;
  width: 30px;
  border-radius: 50%;
  position: relative;
  cursor: pointer;
  color: white;
  padding: 1px;
  font-size: 1.8rem;
  justify-content: center;
  align-items: center;
}

.badge {
  display: flex;
  position: absolute;
  background: red;
  height: 7px;
  width: 7px;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  right: -7px;
  top: -7px;
  padding: 8px;
  color: #fff;
  font-size: .8rem;
  font-weight: 500;
}
<!DOCTYPE html>
<html>

<head>
  <meta name = "viewport" content = "width=device-width, initial-scale=1">
  <link rel = "stylesheet" href = "https://maxst.icons8.com/vue-static/landings/line-awesome/line-awesome/1.3.0/css/line-awesome.min.css">
</head>

<body>

  <header>
    <div class = "header-content">
      <div class = "dropdown">
        <a>
          <div onclick = "myFunction(1)" href = "#" class = "notification dropbtn las la-envelope"></div>
          <span onclick = "myFunction(1)" class = "badge dropbtn">4</span>
        </a>

        <div id = "myDropdown1" class = "dropdown-content">
          <div class = "arrow_box">
            <div class = "header-dropdown">
              <ul>
                <li><a href = ""><small>Message content</small></a></li>
                <li><a href = ""><small>Message content</small></a></li>
              </ul>
            </div>
          </div>
        </div>
      </div>

      <div class = "dropdown">
        <a>
          <div onclick = "myFunction(2)" href = "#" class = "notification dropbtn las la-bell"></div>
          <span onclick = "myFunction(2)" class = "badge dropbtn">8</span>
        </a>

        <div id = "myDropdown2" class = "dropdown-content">
          <div class = "arrow_box">
            <div class = "header-dropdown">
              <ul>
                <li><a href = ""><span class = "las la-question"><small>FAQ</small></span></a></li>
                <li><a href = ""><span class = "las la-user"><small>Profile</small></span></a></li>
                <li><a href = ""><span class = "las la-cog"><small>Settings</small></span></a></li>
                <li><a href = ""><span class = "las la-sign-out-alt"><small>Log out</small></span></a></li>
              </ul>
            </div>
          </div>
        </div>
      </div>

    </div>
  </header>
</body>

</html>

Ваше решение не полностью работает, когда вы нажимаете кнопку меню, оно показывает, что все в порядке, но когда вы снова нажимаете кнопку меню, меню остается, что нехорошо.

Eng Khalid Abdi 13.06.2024 22:36

Меню должно исчезнуть (1) когда вы щелкаете за пределами меню (2) когда вы нажимаете, а затем снова вызываете меню; это то, что я хочу

Eng Khalid Abdi 13.06.2024 22:49

проверьте обновление @EngKhalidAbdi

Sagar V 14.06.2024 07:50

Вы можете использовать эти решения. Сначала выберите все myDropdown с помощью [id^='myDropdown'] (выберите все, начиная с myDropdown), затем удалите класс «show» для всех из них, кроме цели (нажали один), а затем переключите класс «show» для цели (так что если щелкнуть один раз, показ будет добавлен, а второй будет удален). Или второй метод, выбрав все, на что не нажали (цель), используя allMenu = document.querySelectorAll([id^='myDropdown']:not(#myDropdown${num})), удалив из них класс показа, а затем просто переключив класс показа. по цели (сохранил это и прокомментировал первое решение)

function myFunction(num) {
    const target = document.getElementById("myDropdown" + num)
    const allMenu = document.querySelectorAll(`[id^='myDropdown']:not(#myDropdown${num})`)
    console.info(allMenu)
      allMenu.forEach(menu=>{
            menu.classList.remove('show')
      })
    target.classList.toggle("show")
 }
 
 window.onclick = function(event) {
    if (!event.target.matches('.dropbtn')) {
       var dropdowns = document.getElementsByClassName("dropdown-content");
       var i;
       for (i = 0; i < dropdowns.length; i++) {
          var openDropdown = dropdowns[i];
          if (openDropdown.classList.contains('show')) {
             openDropdown.classList.remove('show');
          }
       }
    }
 }

/*commented solution
function myFunction(num) {
    const target = document.getElementById("myDropdown" + num)
    const allMenu = document.querySelectorAll("[id^='myDropdown']")
    console.info(allMenu)
    allMenu.forEach(menu=>{
        if (menu!=target){
         menu.classList.remove('show')
        }
    })
    target.classList.toggle("show")
 }
 
 window.onclick = function(event) {
    if (!event.target.matches('.dropbtn')) {
       var dropdowns = document.getElementsByClassName("dropdown-content");
       var i;
       for (i = 0; i < dropdowns.length; i++) {
          var openDropdown = dropdowns[i];
          if (openDropdown.classList.contains('show')) {
             openDropdown.classList.remove('show');
          }
       }
    }
 }
 */
.ul {
  
}
header {
    position: fixed;
    right: 0;
    top: 0;
    left: 0;
    z-index: 100;
    height: 60px;
    box-shadow: 0px 5px 5px -5px rgb(0 0 0 /10%);
    background: #4891c4;;
    color: #ffffff;
    transition: left 300ms;
}

.header-content {
    position: relative;
    top: 0;
    width: 200px;
    height: 60px;
    float: right;
    align-items: center;
    justify-content: center;
}

.header-content, .header-menu {
    display: flex;
    align-items: center;
}

.header-content {
    justify-content: space-between;
    padding: 0rem 1rem;
}

.header-content label:first-child span {
    font-size: 1.3rem;
}

.header-content label {
    cursor: pointer;
}

.arrow_box {
    top: 10px;
    position: relative;
    border: 1px solid #aaa;         /*set border colour here*/
    width: 300px;
    height: auto;
    background-color: #d6eef9;      /*set menu container background color here*/
    border-radius: 3px;
    -webkit-filter: drop-shadow(0 1px 10px rgba(113, 158, 206, 0.8)); /*set shadow colour  and size here*/
    -moz-box-shadow: 0 1px 10px rgba(113, 158, 206, 0.8);
    filter: drop-shadow(0 1px 10px rgba(113, 158, 206, 0.8));
}

.arrow_box:after,
.arrow_box:before {
    bottom: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
}

.arrow_box:after {
    border-color: rgba(255, 255, 255, 0);
    border-bottom-color: #d6eef9;
    border-width: 10px;
    right: 8px;
    margin-right: 0px;
}

.dropdown { 
    display: flex;
    height: 40px;
    width: 40px;
    border-radius: 50%;
    position: relative;
    justify-content: center;
    align-items: center;    
    margin-right: 1rem;
}

.dropdown-content {
    display: none;
    position: absolute;
    min-width: 160px;
    overflow: none;
    z-index: 1;
    right: 0;
    margin-right: 0rem;
    top: calc(100% + 0rem);
}
  
.header-dropdown {
    background-color: #d6eef9; 
}

.header-dropdown ul li:hover {
    background: #d8e2ec;
}
.header-dropdown ul {
    list-style-type: none;
    padding: 0;
    text-align: center;
}
.header-dropdown a {
    text-decoration: none;
    color: var(--menu-color);
    display: block;
    padding: 0.5rem 0rem 0.5rem 1rem;   /* control menu height here */
    text-align: left;       /* control menu text align here center, left or right */
}
.header-dropdown a span {
    min-height: 15px;
    display: inline-flex;
    align-items: center;
    font-size: 1.7rem;
    margin: 0rem 0.5rem 0rem 0.5rem !important;
}
.header-dropdown a span, .header-dropdown a small {
    color: #327091;
}
.header-dropdown a small {
    font-size: 0.95rem;                             /* Sidebar font size */
    font-weight: normal;
    margin: 0rem 1rem 0rem 1rem !important;
    font-family: 'Open Sans', sans-serif;
}

 
.dropbtn {
    border: none;
    cursor: pointer;
}

.show {
    display: block;
}

.notification { 
    display: flex;
    height: 30px;
    width: 30px;
    border-radius: 50%;
    position: relative;
    cursor: pointer;
    color: white;
    padding: 1px;       
    font-size: 1.8rem;
    justify-content: center;
    align-items: center;
}

.badge {
    display: flex;
    position: absolute;
    background: red;
    height: 7px;
    width: 7px;
    justify-content: center;
    align-items: center;
    border-radius: 50%;
    right: -7px;
    top: -7px;
    padding: 8px;
    color: #fff;
    font-size: .8rem;
    font-weight: 500;
}
<link rel = "stylesheet" href = "https://maxst.icons8.com/vue-static/landings/line-awesome/line-awesome/1.3.0/css/line-awesome.min.css">
   
<header>
<div class = "header-content">
    <div class = "dropdown">
        <a>
          <div onclick = "myFunction(1)" href = "#" class = "notification dropbtn las la-envelope"></div>
          <span onclick = "myFunction(1)" class = "badge dropbtn">4</span>
        </a>
        
        <div id = "myDropdown1" class = "dropdown-content">                 
                <div class = "arrow_box">
                    <div class = "header-dropdown">
                         <ul>
                            <li><a href = "example.com"><small>Message content</small></a></li>
                            <li><a href = "example.com"><small>Message content</small></a></li>
                        </ul>                   
                    </div>
                </div>
            </div>
    </div>
    
    <div class = "dropdown">
        <a>
          <div onclick = "myFunction(2)" href = "#" class = "notification dropbtn las la-bell"></div>
          <span onclick = "myFunction(2)" class = "badge dropbtn">8</span>
        </a>
        
        <div id = "myDropdown2" class = "dropdown-content">                 
            <div class = "arrow_box">
                <div class = "header-dropdown">
                     <ul>
                        <li><a href = "example.com"><span class = "las la-question"><small>FAQ</small></span></a></li>
                        <li><a href = "example.com"><span class = "las la-user"><small>Profile</small></span></a></li>
                        <li><a href = "example.com"><span class = "las la-cog"><small>Settings</small></span></a></li>
                        <li><a href = "example.com"><span class = "las la-sign-out-alt"><small>Log out</small></span></a></li>
                    </ul>                   
                </div>
            </div>
        </div>
    </div>
</div>
</header>

Другие вопросы по теме