Assign forEach to each image via 'img'
P粉998100648
2023-07-28 23:13:59
<p>I'm trying to use forEach in JS under the img tag in HTML. </p><p>This is the variable bobbingPhotos: </p>
<pre class="brush:php;toolbar:false;">bobbingPhotos.forEach(function(photo) {
var randomDelay = Math.random() * 2; // Random delay between 0 and 2 seconds
photo.style.animationDelay = randomDelay 's';
});</pre>
<p>This problem could be solved by assigning each image a hardcoded class name "bobbing-photo", but I cannot do this because my images are generated from text input. </p>
<pre class="brush:php;toolbar:false;">function generateImages() {
var userInput = document.getElementById('userInput').value;
var imageOutput = document.getElementById('imageOutput');
imageOutput.innerHTML = '';
for (var i = 0; i < userInput.length; i ) {
var character = userInput[i].toUpperCase();
var element;
if (character === "n") {
element = document.createElement('br');
}
else if (character === ' ') {
element = document.createElement('img');
element.src = 'FONT/SPACE.png';
}
else {
var image = document.createElement('img');
image.src = 'FONT/' character '.png';
element = image;
image.classList.add("bobbing-photo");
}</pre>
<p>Even using image.classList.add("bobbing-photo"), there is no way to make each image float up and down at different points in time. </p><p>Is there any way to solve this problem? </p><p><br /></p>
Since you added the image tag dynamically, the animation function should be called again after adding the image tag.