Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 04.06.2023, 20:20
Профессор
Отправить личное сообщение для Сергей Ракипов Посмотреть профиль Найти все сообщения от Сергей Ракипов
 
Регистрация: 01.06.2010
Сообщений: 651

Навигация по блокам
Я хочу сделать следующее.
Есть две кнопки которые плавно перемещают от блока к блоку 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">
      &uArr;
    </div>
    <div class="nav_down">
      &dArr;
    </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>
Ответить с цитированием
  #2 (permalink)  
Старый 04.06.2023, 20:40
Аватар для Aetae
Тлен
Отправить личное сообщение для Aetae Посмотреть профиль Найти все сообщения от Aetae
 
Регистрация: 02.01.2010
Сообщений: 6,495

А проблема в чём? Тыж расписал что делать надо.
Можешь в чатгпт закинуть, оно те напишет код.)
__________________
29375, 35
Ответить с цитированием
  #3 (permalink)  
Старый 04.06.2023, 21:01
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,072

Сергей Ракипов,
https://javascript.ru/forum/misc/719...tml#post473403
Ответить с цитированием
  #4 (permalink)  
Старый 04.06.2023, 21:31
Профессор
Отправить личное сообщение для Сергей Ракипов Посмотреть профиль Найти все сообщения от Сергей Ракипов
 
Регистрация: 01.06.2010
Сообщений: 651

Сообщение от Aetae Посмотреть сообщение
А проблема в чём? Тыж расписал что делать надо.
Можешь в чатгпт закинуть, оно те напишет код.)
Условия мне не понятно как написать
Ответить с цитированием
  #5 (permalink)  
Старый 04.06.2023, 21:32
Профессор
Отправить личное сообщение для Сергей Ракипов Посмотреть профиль Найти все сообщения от Сергей Ракипов
 
Регистрация: 01.06.2010
Сообщений: 651

рони,
а на JS это нельзя сделать?
Ответить с цитированием
  #6 (permalink)  
Старый 04.06.2023, 21:36
Профессор
Отправить личное сообщение для Сергей Ракипов Посмотреть профиль Найти все сообщения от Сергей Ракипов
 
Регистрация: 01.06.2010
Сообщений: 651

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">
      &uArr;
    </div>
    <div class="nav_down">
      &dArr;
    </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>
Ответить с цитированием
  #7 (permalink)  
Старый 04.06.2023, 23:07
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,072

Навигация по блокам
Сергей Ракипов,
<!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">
            &uArr;
        </div>
        <div class="nav_down">
            &dArr;
        </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>
Ответить с цитированием
  #8 (permalink)  
Старый 05.06.2023, 00:56
Профессор
Отправить личное сообщение для Сергей Ракипов Посмотреть профиль Найти все сообщения от Сергей Ракипов
 
Регистрация: 01.06.2010
Сообщений: 651

рони,
спасибо а почему нету плавности хотя я знаю точно что за плавность вот это отвечает

sections[nextIndex].scrollIntoView({
behavior: "smooth",
block: "start",

я уже так делал, может нужно какую библиотеку подключить?
Ответить с цитированием
  #9 (permalink)  
Старый 05.06.2023, 01:18
Аватар для Aetae
Тлен
Отправить личное сообщение для Aetae Посмотреть профиль Найти все сообщения от Aetae
 
Регистрация: 02.01.2010
Сообщений: 6,495

Сергей Ракипов, плавность есть, мож она у тя просто отключена в браузере?)
__________________
29375, 35
Ответить с цитированием
  #10 (permalink)  
Старый 05.06.2023, 05:28
Профессор
Отправить личное сообщение для Сергей Ракипов Посмотреть профиль Найти все сообщения от Сергей Ракипов
 
Регистрация: 01.06.2010
Сообщений: 651

Aetae,
Это шутка такая? Просто я понимаю что нет таких настроек как плавность в браузере
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Как обойти присвоение одинаковых id двум блокам? NeonMan jQuery 38 01.09.2018 02:17
Скрипт, чтобы текстовым блокам давался красный бекграуд каждому по очереди barakuda jQuery 7 13.04.2016 18:15
скроллинг по блокам ecSpl01t Элементы интерфейса 4 17.09.2014 11:47
скроллинг по блокам ecSpl01t jQuery 0 15.09.2014 21:04
AJAX навигация без якоря(Требуется помощ) Radik55rus AJAX и COMET 11 14.08.2014 10:34