Как сделать чтоб при нажатии на кнопку появлялся задний фон который будет обхватывать первый добавленный левый и правый текст?
У меня есть вот такой код html:
<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-container"> <div id="textContainer_left"></div> <div id="textContainer_rignt"></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-container"> <div id="textContainer_left"></div> <div id="textContainer_rignt"></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>
также вот такой css:
.text-container { display: flex; flex-wrap: wrap; justify-content: space-between; font-size: 30px; margin-top: 10%; margin-left: 8%; width: 500px; height: 330px; padding: 10px; overflow: auto; } #textContainer_rignt { text-align: right; margin-left: 240px; } |
.text-container { display: flex; flex-wrap: wrap; justify-content: space-between; font-size: 30px; margin-top: 10%; margin-left: 8%; width: 500px; height: 330px; padding: 10px; overflow: auto; } #textContainer_rignt { text-align: right; margin-left: 240px; }
и javascript:
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 = 0; function moveBackground() { const textBlocksLeft = document.querySelectorAll('.text-block-left'); const textBlocksRight = document.querySelectorAll('.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 = '1500px'; textBlocksLeft[currentBackgroundPosition].style.borderRadius = '25px'; } if (currentBackgroundPosition < textBlocksRight.length) { textBlocksRight[currentBackgroundPosition].style.marginBottom = '0'; textBlocksRight[currentBackgroundPosition].style.background = 'blue'; textBlocksRight[currentBackgroundPosition].style.borderRadius = '25px'; textBlocksRight[currentBackgroundPosition].parentNode.style.height = 'auto'; } const containerLeft = document.getElementById('textContainer_left'); const containerRight = document.getElementById('textContainer_rignt'); const nextTextBlockLeft = textBlocksLeft[currentBackgroundPosition]; const nextTextBlockRight = textBlocksRight[currentBackgroundPosition]; if (nextTextBlockLeft) { const containerRectLeft = containerLeft.getBoundingClientRect(); const nextTextBlockRectLeft = nextTextBlockLeft.getBoundingClientRect(); const scrollOffsetLeft = nextTextBlockRectLeft.top - containerRectLeft.top; containerLeft.scrollTo({ top: scrollOffsetLeft, behavior: 'smooth' }); } if (nextTextBlockRight) { const containerRectRight = containerRight.getBoundingClientRect(); const nextTextBlockRectRight = nextTextBlockRight.getBoundingClientRect(); const scrollOffsetRight = nextTextBlockRectRight.top - containerRectRight.top; containerRight.scrollTo({ top: scrollOffsetRight, 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 = 0; function moveBackground() { const textBlocksLeft = document.querySelectorAll('.text-block-left'); const textBlocksRight = document.querySelectorAll('.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 = '1500px'; textBlocksLeft[currentBackgroundPosition].style.borderRadius = '25px'; } if (currentBackgroundPosition < textBlocksRight.length) { textBlocksRight[currentBackgroundPosition].style.marginBottom = '0'; textBlocksRight[currentBackgroundPosition].style.background = 'blue'; textBlocksRight[currentBackgroundPosition].style.borderRadius = '25px'; textBlocksRight[currentBackgroundPosition].parentNode.style.height = 'auto'; } const containerLeft = document.getElementById('textContainer_left'); const containerRight = document.getElementById('textContainer_rignt'); const nextTextBlockLeft = textBlocksLeft[currentBackgroundPosition]; const nextTextBlockRight = textBlocksRight[currentBackgroundPosition]; if (nextTextBlockLeft) { const containerRectLeft = containerLeft.getBoundingClientRect(); const nextTextBlockRectLeft = nextTextBlockLeft.getBoundingClientRect(); const scrollOffsetLeft = nextTextBlockRectLeft.top - containerRectLeft.top; containerLeft.scrollTo({ top: scrollOffsetLeft, behavior: 'smooth' }); } if (nextTextBlockRight) { const containerRectRight = containerRight.getBoundingClientRect(); const nextTextBlockRectRight = nextTextBlockRight.getBoundingClientRect(); const scrollOffsetRight = nextTextBlockRectRight.top - containerRectRight.top; containerRight.scrollTo({ top: scrollOffsetRight, behavior: 'smooth' }); } }
проблема заключается в том что когда я нажимаю на кнопку правый текст уходит в низ,подскажите как сделать так чтоб он не уходил в низ и перемещялся задний фон как по левому так и по правому
Дополнительно:
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопрос
Для реализации данного функционала вам понадобится использовать JavaScript. Вот пример кода, который позволит вам добиться желаемого эффекта:
```html
#overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 999;
}
#content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
text-align: center;
}
Левый текст
Правый текст
function toggleOverlay() {
var overlay = document.getElementById('overlay');
if (overlay.style.display === 'block') {
overlay.style.display = 'none';
} else {
overlay.style.display = 'block';
}
}
```
В данном примере при нажатии на кнопку будет показываться задний фон (черный полупрозрачный слой), на котором будет располагаться текст. Таким образом, при появлении фона, левый и правый текст будут обхвачены задним фоном.
Вы можете настраивать стиль и содержимое текста в блоке `#content` в соответствии с вашими потребностями. А функцию `toggleOverlay()` можно дополнить другими эффектами, например, анимацией появления и исчезновения фона.
Надеюсь, этот код поможет вам реализовать нужный функционал на вашем веб-сайте. Если у вас возникнут дополнительные вопросы, не стесняйтесь задавать!