Как сделать чтоб скрол двигался с задним фоном?

Ссылка скопирована
23 января 2026 1 ответ
<div class="bloc_sum">         <h3 class="sum" id="sum">0</h3>         <h3 class="played" id="played">0</h3>         <div class="cup" id="cyp_bon">0</div>     </div>          <div class="text-wrapper">         <div class="text-container" id="textContainer_left">           <div id="textContainer_left"></div>         </div>                <div class="text-container" id="textContainer_rignt">           <div id="textContainer_rignt"></div>         </div>     </div>      <div class="content_pol"><textarea id="content" rows="3" cols="30"></textarea></div>     <div class="content_slot" onclick="addText()">Добавить текст с лева</div>          <div class="contentIndented"><textarea id="contentIndented" rows="3" cols="30"></textarea></div>     <div class="content_sum" onclick="addIndentedText()">Добавить текст с права</div>     <div class="move" onclick="moveBackground()">Следующий текст</div>

<div class="bloc_sum"> <h3 class="sum" id="sum">0</h3> <h3 class="played" id="played">0</h3> <div class="cup" id="cyp_bon">0</div> </div> <div class="text-wrapper"> <div class="text-container" id="textContainer_left"> <div id="textContainer_left"></div> </div> <div class="text-container" id="textContainer_rignt"> <div id="textContainer_rignt"></div> </div> </div> <div class="content_pol"><textarea id="content" rows="3" cols="30"></textarea></div> <div class="content_slot" onclick="addText()">Добавить текст с лева</div> <div class="contentIndented"><textarea id="contentIndented" rows="3" cols="30"></textarea></div> <div class="content_sum" onclick="addIndentedText()">Добавить текст с права</div> <div class="move" onclick="moveBackground()">Следующий текст</div>

let counter = 1; let previousTextBlock = null; let previousIndentedTextBlock = null; let total = 0; let sum = 0;   function addText() {   const content = document.getElementById('content').value;   const counterElement = document.getElementById('cyp_bon');     if (!counterElement.textContent) {     counterElement.textContent = '0';   }     const textBlock = document.createElement('div');   textBlock.classList.add('text-block-left');   textBlock.textContent = content;     textBlock.addEventListener('click', function () {     if (!textBlock.isEditing) {       const input = document.createElement('input');       input.type = 'text';       input.value = textBlock.textContent;       textBlock.textContent = '';       textBlock.appendChild(input);       input.focus();       textBlock.isEditing = true;       textBlock.style.fontSize = '30px';         input.addEventListener('blur', function () {         textBlock.textContent = input.value;         textBlock.isEditing = false;       });     }   });     const textContainer_left = document.getElementById('textContainer_left');   textContainer_left.appendChild(textBlock);     document.getElementById('content').value = '';     if (previousTextBlock !== null) {     previousTextBlock.style.marginBottom = '10px';     previousTextBlock.style.background = '';   }     previousTextBlock = textBlock;     const counter = parseInt(counterElement.textContent) + 1;     counterElement.textContent = counter.toString();  }   function addIndentedText() {   const contentIndented = document.getElementById('contentIndented').value;     const textBlockIndented = document.createElement('div');   textBlockIndented.classList.add('textContainer_right');   textBlockIndented.textContent = contentIndented;     textBlockIndented.addEventListener('click', function () {     if (!textBlockIndented.isEditing) {       const input = document.createElement('input');       input.type = 'text';       input.value = textBlockIndented.textContent;       textBlockIndented.textContent = '';       textBlockIndented.appendChild(input);       input.focus();       textBlockIndented.isEditing = true;         input.addEventListener('blur', function () {         textBlockIndented.textContent = input.value;         textBlockIndented.isEditing = false;         updateSum();       });     }   });     const textContainer_rignt = document.getElementById('textContainer_rignt');   textContainer_rignt.appendChild(textBlockIndented);     document.getElementById('contentIndented').value = '';     if (previousIndentedTextBlock !== null) {     previousIndentedTextBlock.style.marginBottom = '10px';     previousIndentedTextBlock.style.background = '';   }     previousIndentedTextBlock = textBlockIndented;     updateSum(); }   function updateSum() {   let sum = 0;     const textBlocks = document.querySelectorAll('.textContainer_right');   textBlocks.forEach(function (textBlock) {     const content = textBlock.textContent.trim();     const regex = /=s*(d+)/;     const match = regex.exec(content);     if (match) {       const number = parseInt(match[1]);       if (!isNaN(number)) {         sum += number;       }     }   });     const sumElement = document.getElementById('sum');   const sumValue = parseFloat(sumElement.textContent);   if (!isNaN(sumValue)) {     sum -= sumValue;   }     const playedElement = document.getElementById('played');   playedElement.textContent = isNaN(sum) ? '0' : sum.toString(); }   var currentBackgroundPosition = -1;   function moveBackground() {   const textBlocksLeft = document.querySelectorAll('.text-wrapper #textContainer_left .text-block-left');   const textBlocksRight = document.querySelectorAll('.text-wrapper #textContainer_rignt .textContainer_right');   const numTextBlocks = Math.max(textBlocksLeft.length, textBlocksRight.length);    if (numTextBlocks === 0) {     return;   }    currentBackgroundPosition++;    if (currentBackgroundPosition >= numTextBlocks) {     currentBackgroundPosition = 0;   }    textBlocksLeft.forEach(function (textBlockLeft) {     textBlockLeft.style.marginBottom = '10px';     textBlockLeft.style.background = '';   });    textBlocksRight.forEach(function (textBlockRight) {     textBlockRight.style.marginBottom = '10px';     textBlockRight.style.background = '';   });    if (currentBackgroundPosition < textBlocksLeft.length) {     textBlocksLeft[currentBackgroundPosition].style.marginBottom = '0';     textBlocksLeft[currentBackgroundPosition].style.background = 'blue';     textBlocksLeft[currentBackgroundPosition].style.width = '100%';     textBlocksLeft[currentBackgroundPosition].style.borderRadius = '5px';   }    if (currentBackgroundPosition < textBlocksRight.length) {     textBlocksRight[currentBackgroundPosition].style.marginBottom = '0';     textBlocksRight[currentBackgroundPosition].style.background = 'blue';     textBlocksRight[currentBackgroundPosition].style.borderRadius = '5px';   }    const containerLeft = document.getElementById('textContainer_left');   const containerRight = document.getElementById('textContainer_rignt');    if (currentBackgroundPosition < textBlocksLeft.length) {     containerLeft.scrollTo({       top: textBlocksLeft[currentBackgroundPosition].offsetTop - 150,       behavior: 'smooth'     });   }       if (currentBackgroundPosition < textBlocksRight.length) {     containerRight.scrollTo({       top: textBlocksRight[currentBackgroundPosition].offsetTop - 150,       behavior: 'smooth'     });   } }

let counter = 1; let previousTextBlock = null; let previousIndentedTextBlock = null; let total = 0; let sum = 0; function addText() { const content = document.getElementById('content').value; const counterElement = document.getElementById('cyp_bon'); if (!counterElement.textContent) { counterElement.textContent = '0'; } const textBlock = document.createElement('div'); textBlock.classList.add('text-block-left'); textBlock.textContent = content; textBlock.addEventListener('click', function () { if (!textBlock.isEditing) { const input = document.createElement('input'); input.type = 'text'; input.value = textBlock.textContent; textBlock.textContent = ''; textBlock.appendChild(input); input.focus(); textBlock.isEditing = true; textBlock.style.fontSize = '30px'; input.addEventListener('blur', function () { textBlock.textContent = input.value; textBlock.isEditing = false; }); } }); const textContainer_left = document.getElementById('textContainer_left'); textContainer_left.appendChild(textBlock); document.getElementById('content').value = ''; if (previousTextBlock !== null) { previousTextBlock.style.marginBottom = '10px'; previousTextBlock.style.background = ''; } previousTextBlock = textBlock; const counter = parseInt(counterElement.textContent) + 1; counterElement.textContent = counter.toString(); } function addIndentedText() { const contentIndented = document.getElementById('contentIndented').value; const textBlockIndented = document.createElement('div'); textBlockIndented.classList.add('textContainer_right'); textBlockIndented.textContent = contentIndented; textBlockIndented.addEventListener('click', function () { if (!textBlockIndented.isEditing) { const input = document.createElement('input'); input.type = 'text'; input.value = textBlockIndented.textContent; textBlockIndented.textContent = ''; textBlockIndented.appendChild(input); input.focus(); textBlockIndented.isEditing = true; input.addEventListener('blur', function () { textBlockIndented.textContent = input.value; textBlockIndented.isEditing = false; updateSum(); }); } }); const textContainer_rignt = document.getElementById('textContainer_rignt'); textContainer_rignt.appendChild(textBlockIndented); document.getElementById('contentIndented').value = ''; if (previousIndentedTextBlock !== null) { previousIndentedTextBlock.style.marginBottom = '10px'; previousIndentedTextBlock.style.background = ''; } previousIndentedTextBlock = textBlockIndented; updateSum(); } function updateSum() { let sum = 0; const textBlocks = document.querySelectorAll('.textContainer_right'); textBlocks.forEach(function (textBlock) { const content = textBlock.textContent.trim(); const regex = /=s*(d+)/; const match = regex.exec(content); if (match) { const number = parseInt(match[1]); if (!isNaN(number)) { sum += number; } } }); const sumElement = document.getElementById('sum'); const sumValue = parseFloat(sumElement.textContent); if (!isNaN(sumValue)) { sum -= sumValue; } const playedElement = document.getElementById('played'); playedElement.textContent = isNaN(sum) ? '0' : sum.toString(); } var currentBackgroundPosition = -1; function moveBackground() { const textBlocksLeft = document.querySelectorAll('.text-wrapper #textContainer_left .text-block-left'); const textBlocksRight = document.querySelectorAll('.text-wrapper #textContainer_rignt .textContainer_right'); const numTextBlocks = Math.max(textBlocksLeft.length, textBlocksRight.length); if (numTextBlocks === 0) { return; } currentBackgroundPosition++; if (currentBackgroundPosition >= numTextBlocks) { currentBackgroundPosition = 0; } textBlocksLeft.forEach(function (textBlockLeft) { textBlockLeft.style.marginBottom = '10px'; textBlockLeft.style.background = ''; }); textBlocksRight.forEach(function (textBlockRight) { textBlockRight.style.marginBottom = '10px'; textBlockRight.style.background = ''; }); if (currentBackgroundPosition < textBlocksLeft.length) { textBlocksLeft[currentBackgroundPosition].style.marginBottom = '0'; textBlocksLeft[currentBackgroundPosition].style.background = 'blue'; textBlocksLeft[currentBackgroundPosition].style.width = '100%'; textBlocksLeft[currentBackgroundPosition].style.borderRadius = '5px'; } if (currentBackgroundPosition < textBlocksRight.length) { textBlocksRight[currentBackgroundPosition].style.marginBottom = '0'; textBlocksRight[currentBackgroundPosition].style.background = 'blue'; textBlocksRight[currentBackgroundPosition].style.borderRadius = '5px'; } const containerLeft = document.getElementById('textContainer_left'); const containerRight = document.getElementById('textContainer_rignt'); if (currentBackgroundPosition < textBlocksLeft.length) { containerLeft.scrollTo({ top: textBlocksLeft[currentBackgroundPosition].offsetTop - 150, behavior: 'smooth' }); } if (currentBackgroundPosition < textBlocksRight.length) { containerRight.scrollTo({ top: textBlocksRight[currentBackgroundPosition].offsetTop - 150, behavior: 'smooth' }); } }

.text-wrapper {     display: flex;     justify-content: space-between;     font-size: 30px;     margin-top: 10%;     margin-left: 8%;     width: 500px;     height: 330px;     padding: 10px; }    .text-container {     width: 50%;     overflow: hidden; }    #textContainer_rignt {     text-align: right;     margin-left: 0; }

.text-wrapper { display: flex; justify-content: space-between; font-size: 30px; margin-top: 10%; margin-left: 8%; width: 500px; height: 330px; padding: 10px; } .text-container { width: 50%; overflow: hidden; } #textContainer_rignt { text-align: right; margin-left: 0; }

Я смог реализовать через 2 скрола, подскажите как сделать чтоб он был 1 и двигался вместе с задним фоном

Дополнительно:

background-attachment?

  • Вадим, не в этой ситуации, если вы смотрели код то там по нажатию на кнопку перемещяеться задний фон на тексте
  • Tolic1, конечно не смотрел(ну то есть смотрел, по диагонале, что конечно же не даёт понимания в чём проблема). Мало кто будет сидеть и читать такое полотно и компилировать в голове в чём же вопрос.
    Хотите чтобы помогли быстрее а ответы были точнее - делайте демку на codepen и чётче демонстрируйте в чём проблема.
  • Вадим, https://codepen.io/etseyvwl-the-sans/pen/bGQgQOM ,думаю так вы мне больше поможете, спасибо за подсказку
  • Tolic1, так, а что мешает задать фон для .textContainer_right(и не убирать его при нажатии на "кнопку", которая совсем не кнопка...) и сделать background-attachment(который может и не нужен будет, если это просто цвет, а не картинка)?
  • Вадим, нужно именно чтоб текст был с задним фоном и по нажатию на "кнопку" он переходил к другому другому тексту ,такая задача стояла передомной,я смог лиж реализовать через 2 скрол это всё
  • Tolic1, Ладно, мы с Вами так будет очень долго выяснять что же Вам всё же нужно и что мешает Вам зафиксировать фон.
    А играть в угадайку дело не благодарное.

    Так что вот моё последнее предложение:

    #textContainer_right, #textContainer_left {   background-attachment: fixed; }

    #textContainer_right, #textContainer_left { background-attachment: fixed; }

    И я убрал все строчки в JS которые обнуляли фон, типа такой:
    textBlockRight.style.background = '';

    Выглядит будто бы это очень близко к тому, чего Вы ожидаете, как я это понял.

  • Вадим, я не правильно видимо задал вопрос, извините, подскажите как сделать чтоб правый блок был также как и левый https://codepen.io/etseyvwl-the-sans/pen/bGQgQOM ,до этого я вам скидывал код который был реализован и к правому тексту тоже, но было криво в том плане что если в какойто блок я добавлял больше текста и он уже показывал задний фон на тексте криво
  • Нужно решить такую задачу?

    Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.

    Заказать помощь
    Лучший ответ
    1
    Елена Вебер Ответ

    Для того чтобы создать эффект, когда скролл двигается с задним фоном, можно использовать CSS свойство background-attachment. Это свойство позволяет контролировать способ, каким фоновое изображение прикрепляется к элементу при прокрутке страницы.

    Для создания эффекта скролла с задним фоном, вам нужно установить значение этого свойства в fixed для фонового изображения. Это зафиксирует фон на месте, когда пользователь прокручивает страницу. Вот как это можно сделать в CSS:

    body {
        background-image: url('your-background-image.jpg');
        background-attachment: fixed;
    }

    body { background-image: url('your-background-image.jpg'); background-attachment: fixed; }

    Примените этот CSS к элементу body или любому другому элементу, который вы хотите сделать с фоновым изображением, которое остается на месте при прокрутке. Убедитесь, что ваше фоновое изображение имеет достаточно высокое разрешение, чтобы оно выглядело хорошо на различных экранах.

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

    Другие ответы (0)

    Пока нет других ответов. Будьте первым, кто поможет автору.

    Ответить на вопрос

    комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *

    Вам также может быть интересно