gpt4 book ai didi

javascript - 在 Javascript 中放置图像

转载 作者:行者123 更新时间:2023-11-29 21:31:46 25 4
gpt4 key购买 nike

我有一个关于在 JS 中将图像加载到数组中然后将它们附加到您网站的不同位置的问题。

假设我有一个包含 3 张图像的文件夹,我想将其加载到一个数组中,然后放置在此设置中

 <body> 

<div id = "mainImage1"></div>
<div id = "mainImage2"></div>
<div id = "mainImage3"></div>
</body>

是否可以加载图像,首先将其放入一个通用数组中,然后将这些图像放入它们的 div 中?

有点像这样? (此代码不正确)

var mainImage1 = document.getElementById("mainImage1");
var mainImage2 = document.getElementById("mainImage2");
var mainImage3 = document.getElementById("mainImage3");

var mainImageSelection = new Image();

mainImageSelection.src = "Images/" + mainImageSelection[i];

mainImage1.appendChild(mainImageSelection[0]);
mainImage2.appendChild(mainImageSelection[1]);

最佳答案

更动态的方式:

var mainImage1 = document.getElementById("mainImage1");
var mainImage2 = document.getElementById("mainImage2");
var mainImage3 = document.getElementById("mainImage3");
var myArr = [mainImage1,mainImage2,mainImage3];
var images = ["https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg","https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg","https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg"]

for(var i=0;i<myArr.length;i++){
var mainImageSelection = new Image();
mainImageSelection.src = images[i];
var div = myArr[i];
div.appendChild(mainImageSelection);
};

fiddle [示例] https://jsfiddle.net/h1t4vxy6/1/

关于javascript - 在 Javascript 中放置图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36132950/

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