Как сделать так, чтобы 2 отдельных элемента div по очереди располагались вверху страницы?

Я хочу сделать 2 липких заголовка div вверху при прокрутке страницы.

FIRST DIV попадает в палка только на некоторое время, пока SECOND DIV не появится в определенной точке экрана.

Когда SECOND DIV при прокрутке вверх достигает половины страницы (например), FIRST DIV перестает быть липкий, отталкивается, а затем заменяется SECOND DIV как следующий липкий элемент вверху.

Мне удалось заставить первый div прилипнуть к вершине с помощью моего CSS, но я понятия не имею, что делать с second div.

.body {
  margin: 0;
}

h3 {
  background-color: #E9BDF5;
  width: 100%;
}

.firstDiv {
  text-align: center;
  background-color: yellow;
  width: 100%;
  height: 70px;
  position: sticky;
  top: 0;
}

.secondDiv {
  text-align: center;
  background-color: yellow;
  width: 100%;
  height: 60px;
}
<h3>These text don't stick</h3>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and
</p>

<div class = "firstDiv">
  <h2>First Div - Becomes sticky (temporarily)</h2>
</div>

<h3>These text don't stick</h3>

<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>

<div class = "secondDiv">
  <h2>Second Div - Becomes the sticky header</h2>
</div>

<h3>These text don't stick</h3>

<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and will not stick at the top
</p>

Любые советы по этому поводу будут высоко оценены. Заранее благодарю вас за вашу любезную помощь ??♥️

Можете ли вы показать мне, как, пожалуйста?

Hun 18.03.2022 23:07

Попробуйте это: stackoverflow.com/questions/26663602/…

Caio Oliveira 18.03.2022 23:10
Поведение ключевого слова "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) для оценки ваших знаний,...
3
2
38
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

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

Хитрость заключается в использовании обертки div, которая действует как граница для position: sticky;

html {
  font-size: 150%;
}

.firstDiv,
.secondDiv {
  position: sticky;
  top: 0;
  background-color: white;
}
<h3>These text don't stick</h3>
<p>
  This paragraph will scroll up and will not stick at the top
</p>
<p>
  This paragraph will scroll up and
</p>

<div>
  <div class = "firstDiv">
    <h2>First Div - Becomes sticky (temporarily)</h2>
  </div>

  <h3>These text don't stick</h3>

  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
</div>

<div>
  <div class = "secondDiv">
    <h2>Second Div - Becomes the sticky header</h2>
  </div>

  <h3>These text don't stick</h3>

  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
  <p>
    This paragraph will scroll up and will not stick at the top
  </p>
</div>

Оууу, ты лучший @christiansany. Просто и эффективно. Ваше решение только что спасло мою проблему. Большое тебе спасибо

Hun 18.03.2022 23:53

Рад помочь :D

christiansany 19.03.2022 00:22

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