如何向多个不同尺寸的Div同步添加相同文本与文件内容?
Got it, here's how you can tweak your code to sync both text and file content to multiple divs, plus make it easy to add more divs later without touching your JavaScript:
Step 1: Update Your HTML
First, add a shared class (like target-ad-div) to all the divs that should receive the content—this includes your existing ones and any future divs you add:
<div id="adXL" class="target-ad-div"></div> <div id="adL" class="target-ad-div"></div> <div id="adM" class="target-ad-div"></div> <div id="adS" class="target-ad-div"></div> <!-- Any new divs just need the same class to join the sync --> <div id="adNew" class="target-ad-div"></div>
Step 2: Fix the File Input Handler
Complete your readURL function to loop through all divs with the target-ad-div class and update each one. I’m assuming you’re handling image files (adjust the content update logic if you’re working with other file types):
// File input change listener document.getElementById('getval').addEventListener('change', readURL, true); function readURL() { const file = document.getElementById("getval").files[0]; if (!file) return; // Exit early if no file is selected const reader = new FileReader(); reader.onload = function(e) { // Grab all target divs in one go const targetDivs = document.querySelectorAll('.target-ad-div'); // Update each div with the file content targetDivs.forEach(div => { // Example: Set as background image div.style.backgroundImage = `url(${e.target.result})`; // Alternative: Insert an img tag // div.innerHTML = `<img src="${e.target.result}" alt="Uploaded content">`; }); }; reader.readAsDataURL(file); }
Step 3: Add Text Input Sync
If you have a text input (let’s say with id text-input), add a similar handler to sync text across all target divs:
// Text input sync handler document.getElementById('text-input').addEventListener('input', syncTextToDivs); function syncTextToDivs(e) { const inputText = e.target.value; const targetDivs = document.querySelectorAll('.target-ad-div'); targetDivs.forEach(div => { // Replace div text with input content div.textContent = inputText; // Or append text if you want to keep existing content (like images) // div.insertAdjacentText('beforeend', inputText); }); }
Why This Works
- Using a class selector (
querySelectorAll('.target-ad-div')) avoids hardcoding individual div IDs, making your code scalable. - When you add new divs later, just slap the
target-ad-divclass on them—no need to edit your JavaScript at all. - The loop ensures every target div gets the exact same content update, keeping everything in sync automatically.
内容的提问来源于stack exchange,提问作者johnny555

