Форум программистов, компьютерный форум, киберфорум
JavaScript для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.85/13: Рейтинг темы: голосов - 13, средняя оценка - 4.85
2 / 2 / 0
Регистрация: 19.03.2019
Сообщений: 54

Как реализовать закрытие меню при выборе пункта меню?

05.06.2021, 23:47. Показов 2517. Ответов 4
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте! Как сделать так, чтобы мобильное меню закрывалось при выборе пункта меню?

Код прилагаю ниже:
https://codepen.io/OlegErshov1996/pen/zYZrBLz

HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<div class="container">
    <header class="header">
        <div class="progress_page">
            <div class="progress_page_bar" id="pageBar"></div>
        </div>
        <div class="wrap header__wrap">
            <nav class="header__nav">
                <ul class="menu header__menu">
                    <li class="menu__element">
                        <a class="menu__link" href="#banner">Главная</a>
                    </li>
                    <li class="menu__element">
                        <a class="menu__link" href="#about_me">О себе</a>
                    </li>
                    <li class="menu__element">
                        <a class="menu__link" href="#skills">Навыки</a>
                    </li>
                    <li class="menu__element">
                        <a class="menu__link" href="#services">Портфолио</a>
                    </li>
                    <li class="menu__element">
                        <a class="menu__link" href="#contacts">Контакты</a>
                    </li>
                </ul>
            </nav>
            <div class="mobile_menu_wrap" id="mobile_menu_wrap">
                <a class="mobile_menu_button" href="#mobile_menu">
                    <span class="mobile_menu_line"></span>
                </a>
                <ul class="mobile_menu_items" id="mobile_menu_items">
                    <li class="mobile_menu_link">
                        <a class="mobile_link" href="#banner">Главная</a>
                    </li>
                    <li class="mobile_menu_link">
                        <a class="mobile_link" href="#about_me" onclick="toggleMenu();">О себе</a>
                    </li>
                    <li class="mobile_menu_link">
                        <a class="mobile_link" href="#skills" onclick="toggleMenu();">Навыки</a>
                    </li>
                    <li class="mobile_menu_link">
                        <a class="mobile_link" href="#services" onclick="toggleMenu();">Портфолио</a>
                    </li>
                    <li class="mobile_menu_link">
                        <a class="mobile_link" href="#contacts" onclick="toggleMenu();">Контакты</a>
                    </li>
                </ul>
            </div>
        </div>
    </header>
    <section class="banner" id="banner">
        <div class="banner__info">
            <h1 class="banner__title">
                Здравствуйте! Мобильное меню появляется при ширине экрана менее 1100рх
            </h1>
        </div>
    </section>
</div>
 
<div class="container about_me_wrap" id="about_me"></div>
 
<div class="container skills_wrap" id="skills"></div>
 
<div class="container services_wrap" id="services"></div>
 
<div class="container contacts_wrap" id="contacts"></div>
CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
*
  margin: 0
  padding: 0
  box-sizing: border-box
 
html
  height: 100%
  scroll-behavior: smooth
 
a
  text-decoration: none
 
body
  width: 100%
  font-family: 'Philosopher', sans-serif
  background-color: blue
 
.container
  min-width: 320px
  max-width: 100%
  margin: 0 auto
 
.wrap
  min-width: 320px
  max-width: 1440px
  margin: 0 auto
  padding: 15px 20px
  
  .header
  border-bottom: 3px solid transparent
  top: 0
  width: 100%
  position: fixed
  background: transparent
  transition: 2s
  z-index: 10
  //opacity: 0.9
 
  .progress_page
    width: 100%
    height: 3px
    background: gray
    top: 0
    left: 0
    right: 0
    position: fixed
    z-index: 7
 
    .progress_page_bar
      height: 3px
      background: orange
      width: 0
      z-index: 8
 
.header__wrap
  display: flex
  flex-wrap: wrap
  justify-content: center
  align-items: center
 
  .header__logo
    .logo
      display: flex
      align-items: center
      margin-top: 15px
 
  .header__nav
    .header__menu
      padding: 0
      margin: 0
 
.active-header
  background: blue
  border-bottom: 3px solid orange
  transition: 2s
  opacity: 1
 
@media (max-width: 600px)
  .header__wrap
 
  .header__logo
    .logo
      width: 70%
 
.menu
  display: flex
  flex-wrap: wrap
  list-style: none
 
  .menu__element
    margin-right: 50px
    font-weight: bold
 
    &:last-child
      margin-right: 0
 
    .menu__link
      display: inline-block
      font-size: 20px
      color: grey
      position: relative
      letter-spacing: 2px
 
      &:hover
        color: orange
        transition: color 0.4s
 
      &::before, &::after
        position: absolute
        width: 100%
        left: 0
        height: 2px
        background-color: orange
        content: ""
        opacity: 0
        transition: opacity 0.4s, transform 0.4s
 
      &::before
        top: -5px
        transform: translateY(-10px)
 
      &::after
        bottom: -5px
        transform: translateY(10px)
 
      &:hover::before, &:hover::after
        opacity: 1
        transform: translateY(0)
 
@media (min-width: 1100px)
  .mobile_menu_button
    display: none
 
  .mobile_menu_wrap
    display: none
 
@media (max-width: 1100px)
  .header__nav
    display: none
 
  .mobile_menu_wrap
    position: relative
 
    .mobile_menu_items
      display: flex
      flex-direction: column
      justify-content: center
      text-align: center
      background: linear-gradient(90deg, rgba(41,56,68,0.93) 0%, rgba(56,75,91,0.79) 50%, rgba(56,66,74,0.93) 100%), url("https://pbs.twimg.com/media/CXibyBhUAAAEGti.jpg:large") center top no-repeat
      list-style: none
      position: fixed
      height: 100vh
      width: 100%
      align-items: center
      margin-left: auto
      clip-path: circle(100px at 115% -15%)
      -webkit-clip-path: circle(100px at 115% -15%)
      transition: all 1s ease-out
      pointer-events: none
      left: 0
      top: 0
      z-index: 4
 
      .mobile_menu_link
        opacity: 0
 
        &:nth-child(1)
          transition: all 0.5s ease 2.2s
 
        &:nth-child(2)
          transition: all 0.5s ease 2.4s
 
        &:nth-child(3)
          transition: all 0.5s ease 2.6s
 
        &:nth-child(4)
          transition: all 0.5s ease 2.8s
 
        &:nth-child(5)
          transition: all 0.5s ease 3s
 
        &:hover
          background-color: rgba(216, 216, 216, 0.2)
          color: orange
          transition: 0.2s
 
    .open_menu
      display: flex
      justify-content: center
      text-align: center
      clip-path: circle(2000px at 90% -20%)
      -webkit-clip-path: circle(2000px at 90% -20%)
      pointer-events: all
      left: 0
      top: 0
      z-index: 4
 
    .mobile_menu_button
      display: block
      width: 40px
      height: 40px
      background-color: grey
      border-radius: 25%
      box-shadow: 0px 0px 10px rgba(255, 112, 67, 1)
      position: fixed
      top: 20px
      right: 20px
      z-index: 5
 
    .mobile_menu_line
      display: block
      height: 2.5px
      width: 18px
      position: absolute
      right: 50%
      top: 50%
      margin-right: -9px
      margin-top: -1px
      background-color: blue
 
      &::before
        content: ''
        margin-top: -6px
        height: 2px
        width: 9px
        left: 9px
        position: absolute
        background-color: blue
        transition: all 0.2s
 
      &::after
        content: ''
        margin-top: 6px
        height: 2px
        width: 9px
        left: 0
        position: absolute
        background-color: blue
        transition: all 0.2s
 
    .mobile_menu_button_active
      .mobile_menu_line
        background-color: transparent
 
        &::before
          transform: rotate(135deg)
          margin-top: 0
          width: 18px
          left: 0
 
        &::after
          transform: rotate(-135deg)
          margin-top: 0
          width: 18px
 
.mobile_link
  color: grey
  text-decoration: none
  font-size: 22px
  font-weight: bold
  z-index: 5
  display: block
  width: 100vw
  padding: 40px 0
 
  &:hover
    color: orange
    transition: 0.4s
 
.fade
  opacity: 1 !important
  transition: opacity 0.8s ease 0.2s !important
 
@media (max-width: 335px)
  .mobile_menu_button
    display: block
    width: 35px
    height: 35px
    background-color: grey
    border-radius: 25%
    box-shadow: 0px 0px 10px rgba(255, 112, 67, 1)
    position: fixed
    top: 25px
    right: 15px
    z-index: 5
 
.banner
  width: 100%
  height: 100vh
  background: black
  position: relative
  overflow: hidden
 
  &:after
    content: ""
    position: absolute
    left: 0
    top: 0
    width: 100%
    height: 100%
    background: #216
    background-attachment: fixed
    background-size: cover
    opacity: 0.3
    animation: animateFon 30s linear infinite
 
@keyframes animateFon
  50%
    transform: scale(1.5)
  100%
    transform: scale(1)
 
.banner__info
  position: absolute
  z-index: 1
  top: 50%
  left: 50%
  width: 100%
  transform: translate(-50%, -50%)
  max-width: 800px
  text-align: center
  padding: 0 40px
  box-sizing: border-box
 
  .banner__title
    color: grey
    font-size: 44px
    text-shadow: 1px 1px 10px black
 
h6
  display: inline
  font-size: 44px
  font-weight: bold
  opacity: 0
  transition: all 0.5s ease
 
  &.fade
    opacity: 1
 
@media (max-width: 600px)
  .banner__title
    font-size: 38px
 
  h6
    font-size: 38px
 
@media (max-width: 420px)
  .banner__title
    font-size: 32px
 
  h6
    font-size: 32px
 
    
.about_me_wrap
  height: 1000px
  background-color: green
  
.skills_wrap
  height: 1000px
  background-color: brown
  
.services_wrap
  height: 1000px
  background-color: yellow
  
.contacts_wrap
  height: 1000px
  background-color: #444857
  
::-webkit-scrollbar 
  width: 4px
 
 
::-webkit-scrollbar-track 
  box-shadow: inset 0 0 5px grey
  border-radius: 4px
 
 
::-webkit-scrollbar-thumb 
  background: black
  border-radius: 6px
 
 
::-webkit-scrollbar-thumb:hover 
  background: rgb(54, 56, 58)
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const mobileMenuButton = document.querySelector('.mobile_menu_button');
const mobileMenuItems = document.querySelector('.mobile_menu_items');
const mobileMenuLink = document.querySelectorAll('.mobile_menu_items .mobile_menu_link');
 
mobileMenuButton.addEventListener('click', () => {
    mobileMenuItems.classList.toggle('open_menu');
    mobileMenuLink.forEach(linkMobile => {
        linkMobile.classList.toggle('fade');
    });
});
 
const link = document.querySelector('.mobile_menu_button');
const menu = document.querySelector('.mobile_menu_wrap');
 
link.onclick = function () {
    link.classList.toggle('mobile_menu_button_active');
    menu.classList.toggle('mobile_menu_wrap_active');
};
 
function toggleMenu() {
    link.classList.remove('mobile_menu_button_active');
    menu.classList.remove('mobile_menu_wrap_active');
};
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
05.06.2021, 23:47
Ответы с готовыми решениями:

Изменение содержимого при выборе пункта из меню
Привет, парни, в общем есть один проект: есть пункты меню, допустим (мобильный интернет, домашний интернет, usb-модем), по каждому из...

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

Установка галочки в пункте меню при выборе данного пункта меню
Есть меню,надо,чтобы при нажатии на пункт меню напротив этого пункта ставилась галочка. Знаю про функцию checkmenuitem,но она устанавливает...

4
Эксперт JS
 Аватар для DrType
6553 / 3624 / 1075
Регистрация: 07.09.2019
Сообщений: 5,877
Записей в блоге: 1
06.06.2021, 01:00
Здравствуйте,
JavaScript
1
2
3
4
5
6
7
8
mobileMenuItems.addEventListener("click", function (e) {
  if (e.target.closest(".mobile_menu_link")) {
    mobileMenuItems.classList.toggle("open_menu");
    mobileMenuLink.forEach((linkMobile) => {
      linkMobile.classList.toggle("fade");
    });
  }
});
1
2 / 2 / 0
Регистрация: 19.03.2019
Сообщений: 54
06.06.2021, 10:28  [ТС]
DrType, Спасибо Вам!

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

Подскажите, пожалуйста, как это поправить?
0
Эксперт JS
 Аватар для DrType
6553 / 3624 / 1075
Регистрация: 07.09.2019
Сообщений: 5,877
Записей в блоге: 1
06.06.2021, 11:01
Лучший ответ Сообщение было отмечено Олег971 как решение

Решение

Действительно, баг.
Попробовал привести всё в порядок:
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const mobileMenuButton = document.querySelector(".mobile_menu_button");
const mobileMenuItems = document.querySelector(".mobile_menu_items");
const mobileMenuLink = document.querySelectorAll(
  ".mobile_menu_items .mobile_menu_link"
);
const menu = document.querySelector(".mobile_menu_wrap");
mobileMenuItems.addEventListener("click", function (e) {
  if (e.target.closest(".mobile_menu_link")) {
    toggle_mobile();
  }
});
mobileMenuButton.onclick = toggle_mobile;
function toggle_mobile() {
  mobileMenuItems.classList.toggle("open_menu");
  mobileMenuLink.forEach((linkMobile) => {
    linkMobile.classList.toggle("fade");
  });
  toggleMenu();
}
function toggleMenu() {
  mobileMenuButton.classList.toggle("mobile_menu_button_active");
  menu.classList.toggle("mobile_menu_wrap_active");
}
1
2 / 2 / 0
Регистрация: 19.03.2019
Сообщений: 54
06.06.2021, 11:14  [ТС]
DrType, Спасибо большое! Сейчас всё отлично работает
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
06.06.2021, 11:14
Помогаю со студенческими работами здесь

Как вызвать ту или иную форму при выборе пункта меню
Добрый день! Я тут пишу терминалку для управление роботом (точнее саму программу написал) и хотел бы её красиво оформить. Все настройки...

Как при выборе пункта меню получить значение элемента формы?
Здравствуйте. Подскажите как получить измененное значение из editText фрагмента при выборе пункта меню? При выборе пункта меню я...

Крах программы при выборе пункта меню
Здравствуйте. Создаю программу, реализующую дек. Необходимо реализовать его через файловые данные. После пары часов работы, решил прогнать...

Движение точек при выборе пункта меню
Здравствуйте! Как можно сделать так, как в этой программе, когда выбираешь первый пункт меню, а затем нажимаешь function one, чтобы так...

Диалоговое окно при выборе пункта меню
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
Воспроизведение звукового файла с помощью SDL3_mixer при касании экрана Android
8Observer8 26.01.2026
Содержание блога SDL3_mixer - это библиотека я для воспроизведения аудио. В отличие от инструкции по добавлению текста код по проигрыванию звука уже содержится в шаблоне примера. Нужно только. . .
Установка Android SDK, NDK, JDK, CMake и т.д.
8Observer8 25.01.2026
Содержание блога Перейдите по ссылке: https:/ / developer. android. com/ studio и в самом низу страницы кликните по архиву "commandlinetools-win-xxxxxx_latest. zip" Извлеките архив и вы увидите. . .
Вывод текста со шрифтом TTF на Android с помощью библиотеки SDL3_ttf
8Observer8 25.01.2026
Содержание блога Если у вас не установлены Android SDK, NDK, JDK, и т. д. то сделайте это по следующей инструкции: Установка Android SDK, NDK, JDK, CMake и т. д. Сборка примера Скачайте. . .
Использование SDL3-callbacks вместо функции main() на Android, Desktop и WebAssembly
8Observer8 24.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
моя боль
iceja 24.01.2026
Выложила интерполяцию кубическими сплайнами www. iceja. net REST сервисы временно не работают, только через Web. Написала за 56 рабочих часов этот сайт с нуля. При помощи perplexity. ai PRO , при. . .
Модель сукцессии микоризы
anaschu 24.01.2026
Решили писать научную статью с неким РОманом
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru