Навигация по блокам
Я хочу сделать следующее.
Есть две кнопки которые плавно перемещают от блока к блоку section вверх или вниз НО! делают они это так. Я должен написать в условиях следующее. Посмотри в границах какого section ты(возможно это nav) находишься и если будет нажат вверх то поднимись к section который выше если нажат вниз то отпусти вниз к section который ниже. Отпускается или подниматься он должен что бы let section = document.querySelector("section")getBoundingClient Rect(); if(section.top <=0) Так же если выше или ниже нету section то кнопки вниз или вверх должен быть присвоен класс not_found Ну и если такое возможно то тоже самая навигация с помощью клавиш ВНИЗ И ВВЕРХ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> body{ font-family: 'Courier New', Courier, monospace; font-size: 16px; } section{ height: 600px; padding: 0px 0px 0px 60px; font-weight: bold; } header{ height: 600px; } footer{ height: 600px; } nav{ position: fixed; top: 30px; left: 8px; right: 0px; } .nav_up{ height: 50px; width: 50px; display: flex; justify-content: center; align-items: center; background-color: #98FB98; color: #fff; font-size: 25px; cursor: pointer; } .nav_down{ display: flex; justify-content: center; align-items: center; height: 50px; width: 50px; background-color: #755D9A; color: #fff; font-size: 24px; cursor: pointer; } .not_found{ opacity: .2; } </style> </head> <body> <nav> <div class="nav_up"> ⇑ </div> <div class="nav_down"> ⇓ </div> </nav> <header> Шапка </header> <section> Блок 1 </section> <section> Блок 2 </section> <section> Блок 3 </section> <section> Блок 4 </section> <section> Блок 5 </section> <section> Блок 6 </section> <section> Блок 7 </section> <section> Блок 8 </section> <footer> Подвал </footer> <script> let navUp = document.querySelector(".nav_up"); let navDown = document.querySelector(".nav_down"); let section = document.querySelector("section"); function moving_through_blocks() { } window.addEventListener("scroll", moving_through_blocks); </script> </body> </html> |
А проблема в чём? Тыж расписал что делать надо.
Можешь в чатгпт закинуть, оно те напишет код.) |
Сергей Ракипов,
https://javascript.ru/forum/misc/719...tml#post473403 |
Цитата:
|
рони,
а на JS это нельзя сделать? |
Aetae,
офигеть он же реально написал только он не работает как нужно )))) нет плавности и кнопка вниз не работает )) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> body{ font-family: 'Courier New', Courier, monospace; font-size: 16px; } section{ height: 600px; padding: 0px 0px 0px 60px; font-weight: bold; } header{ height: 600px; } footer{ height: 600px; } nav{ position: fixed; top: 30px; left: 8px; right: 0px; } .nav_up{ height: 50px; width: 50px; display: flex; justify-content: center; align-items: center; background-color: #98FB98; color: #fff; font-size: 25px; cursor: pointer; } .nav_down{ display: flex; justify-content: center; align-items: center; height: 50px; width: 50px; background-color: #755D9A; color: #fff; font-size: 24px; cursor: pointer; } .not_found{ opacity: .2; } </style> </head> <body> <nav> <div class="nav_up"> ⇑ </div> <div class="nav_down"> ⇓ </div> </nav> <header> Шапка </header> <section> Блок 1 </section> <section> Блок 2 </section> <section> Блок 3 </section> <section> Блок 4 </section> <section> Блок 5 </section> <section> Блок 6 </section> <section> Блок 7 </section> <section> Блок 8 </section> <footer> Подвал </footer> <script> const sections = document.querySelectorAll("section"); const navUp = document.querySelector(".nav_up"); const navDown = document.querySelector(".nav_down"); function movingThroughBlocks() { const currentSection = getCurrentSection(); // добавляем или убираем класс not_found if (!currentSection.previousElementSibling) { navUp.classList.add("not_found"); } else { navUp.classList.remove("not_found"); } if (!currentSection.nextElementSibling) { navDown.classList.add("not_found"); } else { navDown.classList.remove("not_found"); } } function getCurrentSection() { let currentSection = sections[0]; // ищем текущий section sections.forEach((section) => { if (section.getBoundingClientRect().top < 0) { currentSection = section; } }); return currentSection; } function scrollToSection(direction) { const currentSection = getCurrentSection(); let nextSection; if (direction === "up") { nextSection = currentSection.previousElementSibling; } else if (direction === "down") { nextSection = currentSection.nextElementSibling; } if (nextSection) { nextSection.scrollIntoView({ behavior: "smooth", block: "start", }); } } // обработчики для кнопок navUp.addEventListener("click", () => { scrollToSection("up"); }); navDown.addEventListener("click", () => { scrollToSection("down"); }); // обработчики для клавиш вверх и вниз document.addEventListener("keydown", (event) => { if (event.code === "ArrowUp") { scrollToSection("up"); } else if (event.code === "ArrowDown") { scrollToSection("down"); } }); window.addEventListener("scroll", movingThroughBlocks); </script> </body> </html> |
Навигация по блокам
Сергей Ракипов,
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> body { font-family: 'Courier New', Courier, monospace; font-size: 16px; } section { height: 600px; padding: 0px 0px 0px 60px; font-weight: bold; border: 1px solid #8B4513; } header { height: 600px; } footer { height: 600px; } nav { position: fixed; top: 30px; left: 8px; right: 0px; } .nav_up { height: 50px; width: 50px; display: flex; justify-content: center; align-items: center; background-color: #98FB98; color: #fff; font-size: 25px; cursor: pointer; } .nav_down { display: flex; justify-content: center; align-items: center; height: 50px; width: 50px; background-color: #755D9A; color: #fff; font-size: 24px; cursor: pointer; } .not_found { opacity: .2; } </style> </head> <body> <nav> <div class="nav_up"> ⇑ </div> <div class="nav_down"> ⇓ </div> </nav> <header> Шапка </header> <section> Блок 1 </section> <section> Блок 2 </section> <section> Блок 3 </section> <section> Блок 4 </section> <section> Блок 5 </section> <section> Блок 6 </section> <section> Блок 7 </section> <section> Блок 8 </section> <footer> Подвал </footer> <script> const sections = document.querySelectorAll("section"); const navUp = document.querySelector(".nav_up"); const navDown = document.querySelector(".nav_down"); function getCurrentIndex() { let currentIndex = 0, arr = Array.from(sections); let item = arr.slice(0).sort(function(a, b) { return Math.abs(a.getBoundingClientRect().top) - Math.abs(b.getBoundingClientRect().top); })[0]; currentIndex = arr.indexOf(item); return currentIndex; } function scrollToSection(direction) { const currentIndex = getCurrentIndex(); let nextIndex; if (direction === "up") { nextIndex = Math.max(currentIndex - 1, 0); } else if (direction === "down") { nextIndex = Math.min(currentIndex + 1, sections.length - 1); } sections[nextIndex].scrollIntoView({ behavior: "smooth", block: "start", }); } // обработчики для кнопок navUp.addEventListener("click", () => { scrollToSection("up"); }); navDown.addEventListener("click", () => { scrollToSection("down"); }); // обработчики для клавиш вверх и вниз document.addEventListener("keydown", (event) => { event.preventDefault(); if (event.code === "ArrowUp") { scrollToSection("up"); } else if (event.code === "ArrowDown") { scrollToSection("down"); } }); window.addEventListener("scroll", () => { const currentIndex = getCurrentIndex(); const show = Math.abs(sections[currentIndex].getBoundingClientRect().top) < 1; navUp.classList.toggle("not_found", !currentIndex && show); navDown.classList.toggle("not_found", currentIndex == sections.length - 1 && show); }) </script> </body> </html> |
рони,
спасибо а почему нету плавности хотя я знаю точно что за плавность вот это отвечает sections[nextIndex].scrollIntoView({ behavior: "smooth", block: "start", я уже так делал, может нужно какую библиотеку подключить? |
Сергей Ракипов, плавность есть, мож она у тя просто отключена в браузере?)
|
Aetae,
Это шутка такая? Просто я понимаю что нет таких настроек как плавность в браузере |
Часовой пояс GMT +3, время: 05:41. |