Скрипт выпадающего меню javascript

Многоуровневое выпадающее меню (JavaScript)

Кто не любит читать статьи, предлагаю сразу перейти к наглядному примеру или скачать архив с примером 5,30Кб .

Что понадобится

HTML-файл, CSS-файл, JavaScript-файл и маркированный список, который будет в виде древовидной структуры (последовательности выпадающего меню).

HTML

Создаем файл dropdownmenu.html следующего содержания:

CSS

CSS-файл dropdownmenu.css следующего содержания:

JavaScript

И наконец JavaScript-файл dropdownmenu.js , следующего содержания:

Пример

Открываем HTML-файл dropdownmenu.html и на экране видим выпадающее меню.

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

Выпадающее меню 1

Выпадающее меню 2

Заключение

Когда используется несколько меню, могут возникнуть проблемы в браузере Internet Explorer 6 версии (проблема с таймерами). Грамотные JavaScript-программисты без труда смогут доработать скрипт под себя, а верстальщики изменить внешний вид выпадающего меню.

Категории

Читайте также

  • Модальное окно (JavaScript)
  • Округление до знака — JavaScript
  • str_repeat (JavaScript)
  • Ассоциативный массив в JavaScript
  • str_pad (JavaScript)
  • JavaScript md5
  • Строку в массив (JavaScript)
  • Максимальное число (JavaScript)
  • JavaScript setcookie getcookie
  • Перезагрузить страницу (JavaScript)
  • textarea и maxlength (JavaScript)
  • Как удалить элемент DOM (JavaScript)

Комментарии

Отличный скрипт. Жаль что не кроссбраузерный.
В хроме во время загрузки страницы появляется выпадающее меню на доли секунды.

Вход на сайт

Введите данные указанные при регистрации:

Социальные сети

Вы можете быстро войти через социальные сети:

Источник

Как сделать — Кликабельный выпадающий список

Узнать, как создать интерактивное выпадающее меню с помощью CSS и JavaScript.

Выпадающий

Выпадающее меню — это переключаемое меню, которое позволяет пользователю выбрать одно значение из предопределенного списка:

Создание кликабельного выпадающего списка

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

Шаг 1) Добавить HTML:

Пример

Объяснение примера

Используйте любой элемент, чтобы открыть выпадающее меню, например элемент , или

.

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

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

Шаг 2) Добавить CSS:

Пример

/* Кнопка выпадающего списка */
.dropbtn background-color: #3498DB;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
>

/* Кнопка выпадающего меню при наведении и фокусировке */
.dropbtn:hover, .dropbtn:focus background-color: #2980B9;
>

/* Контейнер — необходим для размещения выпадающего содержимого */
.dropdown position: relative;
display: inline-block;
>

/* Выпадающее содержимое (скрыто по умолчанию) */
.dropdown-content display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
>

/* Ссылки внутри выпадающего списка */
.dropdown-content a color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
>

/* Изменение цвета выпадающих ссылок при наведении курсора */
.dropdown-content a:hover

/* Показать выпадающее меню (используйте JS, чтобы добавить этот класс .dropdown-content содержимого, когда пользователь нажимает на кнопку выпадающего списка) */
.show

Объяснение примера

Мы разработали выпадающую кнопку с фоновым цветом, дополнением, эффектом наведения и т.д.

Класс .dropdown использует position:relative , что необходимо, когда мы хотим, чтобы выпадающий контент был размещен прямо под кнопкой выпадающего списка (с помощью position:absolute ).

Класс .dropdown-content класс содержит фактическое выпадающее меню. Он скрыт по умолчанию и будет отображаться при наведении курсора (см. ниже). Примечание в min-width установлено значение 160px. Не стесняйтесь изменить это. Совет: Если вы хотите, чтобы ширина выпадающего контента, чтобы быть так велик, как в раскрывающееся меню, установить width на 100% (и overflow:auto , чтобы включить прокрутку на маленьких экранах).

Вместо использования границы мы использовали свойство box-shadow , чтобы сделать выпадающее меню похожим на»карточку». Мы также используем z-индекс для размещения выпадающего списка перед другими элементами.

Шаг 3) Добавить JavaScript:

Пример

/* Когда пользователь нажимает на кнопку,
переключение между скрытием и отображением раскрывающегося содержимого */
function myFunction() document.getElementById(«myDropdown»).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’);
>
>
>
>

Источник

How to Build a Dropdown Menu with JavaScript

Victor Eke

Victor Eke

How to Build a Dropdown Menu with JavaScript

If you use the internet, you’ve likely used a dropdown menu before. They primarily serve two purposes: collecting user input in web forms, and implementing action/navigation menus in web applications.

Dropdowns are one of the best ways to offer numerous options for a similar collection of elements without needing to compromise an application’s general layout flow. Aside from web apps, they’re also used in standalone software, operating systems, and so on.

In this guide, you’ll learn how to build a dropdown navigation menu using HTML, CSS, and JavaScript.

Here’s a screenshot of what you’ll be building. At the end of this guide, I’ll include the codepen file so you can play around with it.

dropdown-menu-with-css

Now that we’ve covered the fundamentals of the dropdown menu, let’s discuss the steps for how to build one.

Step 1 – Add the Markup for the Dropdown

Since we’ll be using icons in this guide, we need to first import them. For simplicity, we’ll be using a free library called Boxicons. Feel free to pick other alternatives you prefer.

There are several ways to setup Boxicons in your site. But the simplest way is by defining the script tag in the head of your HTML file, like this:

After importing the icons, create a div element with a class of container . This element will contain the button and dropdown menu.

Inside the container, create a button element and give it a class and id of btn . For the button, pass in the button text and the arrow icon.

Here’s the markup for the button.

Next up, we’ll add the markup for the dropdown menu itself. Underneath the button tag, create a div element and give it a class and id of dropdown . Inside the div element, create an a tag for each individual dropdown item and pass in their respective icon and text.

Here’s what the markup looks like:

 
Create New All Drafts Move To Profile Settings Notification Settings

dropdown-menu-markup

It doesn’t look good yet – so let’s start styling the menu.

Step 2 – Style the Dropdown Menu

First we’ll reset the default margin and padding of every element on the page and store some values in variables so we can reuse it throughout our CSS file. Then we’ll give the body element some global styling.

@import url(https://fonts.googleapis.com/css?family=Inter:100,200,300,regular,500,600,700,800,900); * < margin: 0; padding: 0; box-sizing: border-box; font-family: "Inter", sans-serif; --shadow: rgba(0, 0, 0, 0.05) 0px 6px 10px 0px, rgba(0, 0, 0, 0.1) 0px 0px 0px 1px; --color: #166e67; --gap: 0.5rem; --radius: 5px; >body

Next step is styling the button and the dropdown container itself. In order to speed things up, I’ll explain only the important bits of the styling.

Copy the markup below and paste into your CSS file.

.btn < background-color: white; display: flex; align-items: center; justify-content: flex-start; column-gap: var(--gap); padding: 0.6rem; cursor: pointer; border-radius: var(--radius); border: none; box-shadow: var(--shadow); position: relative; >.bx < font-size: 1.1rem; >.dropdown < position: absolute; width: 250px; box-shadow: var(--shadow); border-radius: var(--radius); margin-top: 0.3rem; background: white; >.dropdown a < display: flex; align-items: center; column-gap: var(--gap); padding: 0.8rem 1rem; text-decoration: none; color: black; >.dropdown a:hover

Since dropdown menus are usually placed over elements, the button was positioned relative and the dropdown menu, position absolute. This ensures that both elements will be close to each other and the dropdown menu will be placed over elements. This way, when toggled, it won’t affect the flow of the page.

dropdown-menu-with-css

Now that the dropdown has been styled, we want it to appear only when the button has been clicked rather than immediately. To hide it, we’ll use CSS.

In a previous article I wrote about How to build a modal with JavaScript, we used display: none to hide the modal element initially from the viewport. But the drawback of utilizing this property was that it was not animatable, according to MDN Docs.

So in this guide, we’ll be following a different approach to hide the dropdown menu. This involves combining the visibility and opacity properties together to get the desired result. This method is how GitHub implements its dropdown menu.

github-dropdown-menu

Inside the dropdown class we created earlier, add a visibility property and give it a value of hidden and set the opacity to 0 . Doing this will hide the dropdown menu from the page.

In order to show the modal, we’ll create a separate class called show . This class will hold the visibility property with a value of visible and opacity of 1 . And we can inject this class into the modal using JavaScript in a bit.

Alongside the styling to hide the modal element, we added another class to rotate the arrow icon when the dropdown button is clicked.

Step 3 — Add the Dropdown Functionality

For starters, let’s store our respective elements into variables so they are reusable.

const dropdownBtn = document.getElementById("btn"); const dropdownMenu = document.getElementById("dropdown"); const toggleArrow = document.getElementById("arrow");

The next step is to create a function to toggle the show class on the dropdown element and to rotate the dropdown arrow when the button is clicked. We’ll name this function toggleDropdown .

const toggleDropdown = function () < dropdownMenu.classList.toggle("show"); toggleArrow.classList.toggle("arrow"); >;

And then we can call this function on the dropdown button using the addEventListener method. So anytime the button is clicked, it will fire the function which controls showing and hiding the dropdown menu.

dropdownBtn.addEventListener("click", function (e) < e.stopPropagation(); toggleDropdown(); >);

If you noticed, we added a stopPropagation() method inside the dropdown function. This prevents the function of the button element from being passed down to the parent element, thus stopping the function from running twice. You’ll understand more about this in the next section.

How to Close the Dropdown Menu When a DOM Element is Clicked

Dropdown menus are usually closed in four different ways:

  • By clicking the button that activates it
  • By clicking on any of its child elements
  • By clicking outside of the menu (on the body)
  • By hitting the Escape or down arrow keys

But for this guide, let’s concentrate on the first three.

First we’ll select the root element using document.documentElement . And as before, we’ll pass in the toggleDropdown() function inside.

But this time, we want to define a condition that checks if the dropdown menu contains the show class or not. Only when it does do we want to fire the close function.

document.documentElement.addEventListener("click", function () < if (dropdownMenu.classList.contains("show")) < toggleDropdown(); >>);

And that is how you build a dropdown menu with JavaScript. Below is the codepen file to test this dropdown menu in action.

Conclusion

I sincerely hope you found this post interesting or useful. If you did, kindly share with your friends or subscribe to my blog so you won’t miss any future postings. Thanks for reading.

Источник

Скрипт выпадающего меню javascript

Напишем выпадающее меню в JavaScript или его еще называют dropdown menu. Этот код устанавливает прослушиватель событий на кнопке раскрывающегося списка, которая переключает класс show в раскрывающемся меню.

Напишем выпадающее меню в JavaScript или его еще называют dropdown menu. Этот код устанавливает прослушиватель событий на кнопке раскрывающегося списка, которая переключает класс show в раскрывающемся меню. Он также устанавливает прослушиватель для объекта окна, который закрывает раскрывающееся меню, если пользователь щелкает за его пределами.

Пример, который мы сделаем:

.dropdown < position: relative; display: inline-block; >.dropdown-button < background-color: lightgray; color: black; padding: 16px; font-size: 16px; border: none; cursor: pointer; >.dropdown-menu < position: absolute; top: 100%; left: 0; display: none; background-color: lightgray; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2); z-index: 1; >.dropdown-menu.show < display: block; >.dropdown-menu a < color: black; padding: 12px 16px; text-decoration: none; display: block; >.dropdown-menu a:hover
const dropdownButton = document.querySelector(".dropdown-button"); const dropdownMenu = document.querySelector(".dropdown-menu"); dropdownButton.addEventListener("click", function () < dropdownMenu.classList.toggle("show"); >); // Закрываем раскрывающееся меню, если пользователь щелкнет за его пределами. window.addEventListener("click", function (event) < if (!event.target.matches(".dropdown-button")) < dropdownMenu.classList.remove("show"); >>);

Источник

Читайте также:  Открыть файл linux python
Оцените статью