gpt4 book ai didi

javascript - 向元素添加多个图像的问题(javascript 循环问题)

转载 作者:行者123 更新时间:2023-12-03 07:10:26 25 4
gpt4 key购买 nike

我想在此代码中将数组中的多张照片添加到元素,但它只将数组中的一张照片添加到第一个元素。我尝试添加 for 循环,但我不知道从哪里开始以及从哪里结束循环。您能否使用链接 (codepen) 查看代码?谢谢

let zoomLevel = 1;

const images = [
{
thumb: 'http://localhost:8080/links/works/Print/001.webp',
hires: 'http://localhost:8080/links/works/Print/001.webp'
},
{
thumb: 'https://tasvir-graphic.de/links/works/digital/unterwelt.webp',
hires: 'https://tasvir-graphic.de/links/works/digital/unterwelt.webp'
}
]

// set to random image
let img = images[Math.floor(Math.random() * images.length)];

image.getElementsByTagName('a')[0].setAttribute('href', img.hires);
image.getElementsByTagName('img')[0].setAttribute('src', img.thumb);

const preloadImage = url => {
let img = new Image();
img.src = url;
}

preloadImage(img.hires);

const enterImage = function(e) {
zoom.classList.add('show', 'loading');
clearTimeout(clearSrc);

let posX, posY, touch = false;

if (e.touches) {
posX = e.touches[0].clientX;
posY = e.touches[0].clientY;
touch = true;
} else {
posX = e.clientX;
posY = e.clientY;
}

您可以使用 Codepen HERE. 更好地检查这一点

最佳答案

    const image = document.querySelectorAll('.image');
/* Store the number of all elements with css class 'image' */
let imageElementsCount = image.length;

for (index = 0; index < imageElementsCount; index++)
{
let arrayElementPos = Math.floor(Math.random() * images.length);

/* Receive the requested element from array with image objects */
let imageObject = images[arrayElementPos];

preloadImage(imageObject.hires);

/* Assign received image properties to your html element */
image[index].getElementsByTagName('a')[0].setAttribute('href', imageObject.hires);
image[index].getElementsByTagName('img')[0].setAttribute('src', imageObject.thumb);

image[index].addEventListener('mouseover', enterImage);
image[index].addEventListener('touchstart', enterImage);

image[index].addEventListener('mouseout', leaveImage);
image[index].addEventListener('touchend', leaveImage);

image[index].addEventListener('mousemove', move);
image[index].addEventListener('touchmove', move);

image[index].addEventListener('wheel', e =>
{
e.preventDefault();
e.deltaY > 0 ? zoomLevel-- : zoomLevel++;

if (zoomLevel < 1) zoomLevel = 1;
if (zoomLevel > 5) zoomLevel = 5;

console.log(`zoom level: ${zoomLevel}`);
zoom.style.transform = `scale(${zoomLevel})`;
});
}

循环一直运行,直到所有已创建的 div 都得到分配。

待办事项:

删除行

const image = document.querySelectorAll('.image')[0];

[0].

下一步:查看 for 循环的主体。删除原始代码中的代码行

关于javascript - 向元素添加多个图像的问题(javascript 循环问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64372645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com