首先,我的编码经验包括修改简单的脚本以在我的页面上工作。其次,我搜索并发现了几个类似的问题,但无法完全解决它们。
我需要一些帮助来使用大约 40 张图像数组中的随机图像填充 3x3 表。我目前有一个使用 backgroundImage 属性的工作模板。我想将其更改为使用常规图像而不是背景图像,这样我最终可以添加模态图像。
我认为这行代码是需要更改的
cell1.style.backgroundImage = "url("+images[imagePos]+")";
我尝试了在这里和其他地方找到的几种选择。这两个链接似乎最相关,但我似乎无法将它们放在一起。
使用 Javascript 将图像随机插入到表中 https://stackoverflow.com/questions/23712257/randomly-inserting-images-into-table-using-javascript
在javascript中显示数组中的随机图像 https://stackoverflow.com/questions/14004318/show-random-image-from-array-in-javascript
任何帮助或者如果有更好的解决方案可以指导我,我将不胜感激。
<html>
<head>
<title>Random BG Table</title>
<style>
.cell {
background-position: center;
}
</style>
<script>
var images = new Array();
images.push("images/Image_01.jpg");
images.push("images/Image_02.jpg");
images.push("images/Image_03.jpg");
images.push("images/Image_04.jpg");
images.push("images/Image_05.jpg");
images.push("images/Image_06.jpg");
images.push("images/Image_08.jpg");
images.push("images/Image_09.jpg");
function randomCellBG()
{
var cell1 = document.getElementById("cell1");
var imagePos = Math.round(Math.random()*(images.length-1));
cell1.style.backgroundImage = "url("+images[imagePos]+")";
var cell2 = document.getElementById("cell2");
var imagePos = Math.round(Math.random()*(images.length-1));
cell2.style.backgroundImage = "url("+images[imagePos]+")";
var cell3 = document.getElementById("cell3");
var imagePos = Math.round(Math.random()*(images.length-1));
cell3.style.backgroundImage = "url("+images[imagePos]+")";
var cell4 = document.getElementById("cell4");
var imagePos = Math.round(Math.random()*(images.length-1));
cell4.style.backgroundImage = "url("+images[imagePos]+")";
cell5.style.backgroundColor = "gray"
}
</script>
</head>
<body onLoad="randomCellBG()"><br><br><br>
<table width="600" height="600" border="1" id="mainTable">
<tr>
<td width="200" class="cell" id="cell1"> </td>
<td width="200" class="cell" id="cell2"> </td>
<td width="200" class="cell" id="cell3"> </td>
</tr>
<tr>
<td width="200" class="cell" id="cell4"> </td>
<td width="200" id="cell5">title</td>
</tr>
</table>
</body>
</html>
使用innerHTML属性
function randomCellBG()
{
var cell1 = document.getElementById("cell1");
var imagePos = Math.round(Math.random()*(images.length-1));
cell1.innerHTML = "<img src='"+images[imagePos]+"' />";
var cell2 = document.getElementById("cell2");
var imagePos = Math.round(Math.random()*(images.length-1));
cell1.innerHTML = "<img src='"+images[imagePos]+"' />";
var cell3 = document.getElementById("cell3");
var imagePos = Math.round(Math.random()*(images.length-1));
cell1.innerHTML = "<img src='"+images[imagePos]+"' />";
var cell4 = document.getElementById("cell4");
var imagePos = Math.round(Math.random()*(images.length-1));
cell1.innerHTML = "<img src='"+images[imagePos]+"' />";
cell5.style.backgroundColor = "gray";
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)