Добавьте непрозрачность и переход к фоновому изображению и div

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

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

Это код на основе window.onscroll, и на веб-сайте есть много других элементов, поэтому он нарушает мой код, а фоновое изображение не отображается на веб-сайте.

Поскольку я новичок в манипулировании DOM и анимации. Итак, мне нужна помощь, чтобы

  function scrollPictureChange() {
        var main = document.querySelector(".main"),
          sections = main.querySelectorAll(".section"),
          BG = main.querySelector(".BG"),
          el = document.querySelector(".show"),
          cords,
          index = 0,
          h = window.innerHeight,
          lastIndex = null,
          offset = 0;

        applyBG(0);
        window.addEventListener("scroll", function () {
          scrollY = Math.abs(document.body.getClientRects()[0].top);
          index = Math.floor(scrollY / (h - offset));

          if (index != lastIndex) {
            // on index change
            if (lastIndex != null) {
              applyBG(index);
            }
            lastIndex = index;
          }

          el.innerText = `index : ${index} height : ${h} top : ${scrollY}`;
        });

        function applyBG(index) {
          BG.classList.remove("anim");
          setTimeout(function () {
            BG.style.backgroundImage = `url(${sections[index + 1].getAttribute(
              "BGurl"
            )})`;
            BG.classList.add("anim");
          }, 300);
        }
      }

      window.onload = scrollPictureChange;
      window.onresize = scrollPictureChange;
   
body {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    overflow-x: hidden;
}

.section {
    height: 100vh;
    width: 100%;
    display: flex;
    z-index: 1;
    position: relative;
    background-size: 100% 100% !important;
}

.text {
    margin: auto;
}

.text p {
    font-family: 'Lato';
    font-style: normal;
    font-weight: 500;
    font-size: 18px;
    line-height: 149%;
    color: #263244;
}

.text h1 {
    margin-bottom: 20px;
    font-family: 'Lato';
    font-style: normal;
    font-weight: 700;
    font-size: 50px;
    line-height: 0px;
    color: #FFFFFF;
    margin-bottom: 50px;
}

.text .story-detail {
    width: 300px;
    border-radius: 20px;
    background: radial-gradient(76.31% 191.89% at 13.43% 22.19%, rgba(226, 228, 231, 0.8) 0%, rgba(228, 228, 229, 0.368) 100%);
    backdrop-filter: blur(10px);
    padding: 23px;
}

.text .story-description {
    width: 321px;
    border-radius: 20px;
    background: radial-gradient(76.31% 191.89% at 13.43% 22.19%, rgba(226, 228, 231, 0.8) 0%, rgba(228, 228, 229, 0.368) 100%);
    backdrop-filter: blur(10px);
    padding: 23px;

}

.BG {
    position: fixed;
    z-index: 0;
    opacity: 1;
    transition: opacity 10s ease-in-out;
    height: 100%;
}

.anim {
    opacity: 1;
}

.show {
    color: orange;
}
  <div class = "main">
      <div class = "section BG">
        <div class = "show"></div> 
      </div>
      <div
        class = "section"
        BGurl = "https://i.postimg.cc/9QYL3ytR/mobile-camp.png"
      >
        <div class = "text">
          <div style = "margin-inline: 20px">
            <h1>Our Story</h1>
            <div class = "story-detail">
              <p>
                We saw a gap between what people need and what banks offer. It
                means millions of us aren't getting the banking experience we
                deserve for different reasons.
              </p>
            </div>
          </div>
        </div>
      </div>

      <div
        class = "section"
        BGurl = "https://i.postimg.cc/9QYL3ytR/mobile-camp.png"
      >
        <div class = "text">
          <div style = "margin-inline: 20px">
            <div class = "story-description">
              <p>
                Traditional banks don’t focus on customers' experience, their
                systems may be slow and outdated, they may prioritize a specific
                group of people, or perhaps they lack the ability to innovate,
                and so on.
              </p>
            </div>
          </div>
        </div>
      </div>

      <div
        class = "section"
        BGurl = "https://i.postimg.cc/cLPLS8xW/mobile-desert.png"
      >
        <div class = "text">
          <div style = "margin-inline: 20px">
            <div class = "story-description">
              <p>
                So since we're passionate about solving problems and bridging
                gaps, we looked into and identified the challenges and
                capabilities we'll need to build a bank here in the Kingdom.
              </p>
            </div>
          </div>
        </div>
      </div>

      <div
        class = "section"
        BGurl = "https://i.postimg.cc/mZnqV38T/mobile-birds.png"
      >
        <div class = "text">
          <div style = "margin-inline: 20px">
            <div class = "story-description">
              <p>
                With the best local and international expertise, we began
                building an innovative digital bank designed by and for the
                people. We believe that the most effective way to build a bank
                for people is to do it with them. This is our philosophy. So, we
                started building it with the help of people like you.
              </p>
            </div>
          </div>
        </div>
      </div>
      <div class = "section" BGurl = "https://i.postimg.cc/k513m0Fb/mountain.png">
        <div class = "text">
          <div style = "margin-inline: 20px">
            <div class = "story-description">
              <p>
                At D360, innovation starts with someone’s passion for improving
                financial services. To that person, we say: Never stop offering
                solutions to your needs. These solutions will not only benefit
                you, but will significantly impact the lives of millions.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>

@ Эмре Да, я проверил

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

Ответы 1

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

Больно делать то, что вы хотите, с помощью метода, которому вы следуете. Поэтому я предлагаю метод getBoundingClientRect(). Этот метод представляет собой веб-API, который возвращает информацию о размере элемента и его положении на вашей странице.

Свойства left, top, right, bottom, x, y, width и height описывают положение и размер всего прямоугольника в пикселях. Свойства, отличные от ширины и высоты, относятся к верхнему левому углу окна просмотра.

Источник: Дополнительная информация и примеры


Образец (по вашему вопросу)

  1. Создайте 10 разделов (необязательно)
<div class = "div">
    <p>Sample sentence is here!</p>
</div>
  1. Определить стиль для Div с помощью CSS
.div {
    /* This must be exist. */
    opacity: 0;

    /* OPTIONAL STYLE  */
    width: 300px;
    border:1px solid black;
    border-radius: 20px;
    margin:auto;
    padding: 10px;
    background-color: white;
    transition: opacity 1s;
    margin-bottom: 20px;
}
  1. Установите путь к фоновым изображениям в массиве в JS
const bgImgs = ['https://picsum.photos/id/237/1920/1080','https://picsum.photos/id/102/1920/1080','https://picsum.photos/id/202/1920/1080','https://picsum.photos/id/99/1920/1080','https://picsum.photos/id/63/1920/1080','https://picsum.photos/id/6/1920/1080','https://picsum.photos/id/10/1920/1080','https://picsum.photos/id/19/1920/1080','https://picsum.photos/id/80/1920/1080','https://picsum.photos/id/111/1920/1080'];
  1. Получить все ваши Divs в JS
const divs = document.querySelectorAll('.div');
  1. Получите информацию о каждом Div и сделайте 3 правила с помощью IF-Statement в JS.
for (var i = 0; i < divs.length; i++) {
    const div = divs[i];
    const rect = div.getBoundingClientRect();
    if (rect.top >= 0 && rect.bottom <= window.innerHeight) {
        div.style.opacity = 1;
        document.body.style.backgroundImage = `url('${bgImgs[i]}')`;
    } else if (rect.top < 0 && rect.bottom > 0) {
        div.style.opacity = rect.bottom / window.innerHeight;
    } else if (rect.top > 0 && rect.top < window.innerHeight) {
        div.style.opacity = 1 - (rect.top / window.innerHeight);
    }
}

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

Протестируйте образец

const bgImgs = ['https://picsum.photos/id/237/1920/1080','https://picsum.photos/id/102/1920/1080','https://picsum.photos/id/202/1920/1080','https://picsum.photos/id/99/1920/1080','https://picsum.photos/id/63/1920/1080','https://picsum.photos/id/6/1920/1080','https://picsum.photos/id/10/1920/1080','https://picsum.photos/id/19/1920/1080','https://picsum.photos/id/80/1920/1080','https://picsum.photos/id/111/1920/1080'];
function handleScroll(){
    const divs = document.querySelectorAll('.div');
    for (var i = 0; i < divs.length; i++) {
        const div = divs[i];
        const rect = div.getBoundingClientRect();
        if (rect.top >= 0 && rect.bottom <= window.innerHeight) {
            div.style.opacity = 1;
            document.body.style.backgroundImage = `url('${bgImgs[i]}')`;
        } else if (rect.top < 0 && rect.bottom > 0) {
            div.style.opacity = rect.bottom / window.innerHeight;
        } else if (rect.top > 0 && rect.top < window.innerHeight) {
            div.style.opacity = 1 - (rect.top / window.innerHeight);
        }
    }
};
window.addEventListener('scroll', handleScroll);
handleScroll();
html, body {
    /* OPTIONAL STYLE  */
    margin: 20px 0 20px 0;
    padding: 0;
    transition: background-image 1s;
    
    /* The fixed background image */
    background-repeat: no-repeat;
    background-attachment: fixed;
}
.div {
    /* This must be exist. */
    opacity: 0;

    /* OPTIONAL STYLE  */
    width: 300px;
    border:1px solid black;
    border-radius: 20px;
    margin:auto;
    padding: 10px;
    background-color: white;
    transition: opacity 1s;
    margin-bottom: 20px;
}
<!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>Opacity Divs</title>
</head>
<body>
    <div class = "div">
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
    </div>
    <div class = "div">
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
    </div>
    <div class = "div">
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
    </div>
    <div class = "div">
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
    </div>
    <div class = "div">
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
    </div>
    <div class = "div">
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
    </div>
    <div class = "div">
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
    </div>
    <div class = "div">
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
    </div>
    <div class = "div">
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
    </div>
    <div class = "div">
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
        <p>Traditional banks don’t focus on customers' experience, their systems may be slow and outdated, they may prioritize a specific group of people, or perhaps they lack the ability to innovate, and so on.</p>
        <p>We saw a gap between what people need and what banks offer. It means millions of us aren't getting the banking experience we deserve for different reasons.</p>
    </div>
</body>
</html>

Примечание:

Фоновые изображения могут загружаться немного медленно из-за размера. Рекомендуется хранить фоновые изображения в файле local.

Прохладный. Почему фон прокручивается с помощью div. Фон должен быть липким или фиксированным до последней прокрутки карты.

sohaib 04.12.2022 10:12

Я обновил код для вас. Вы можете увидеть изменения в разделе CSS. @sohaib

Emre 05.12.2022 09:06

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