要防止随机生成的桌面镜像在同一个<td>
上生成,可以采用以下几种方法:
<td>
元素:表格数据单元格,用于在HTML表格中显示数据。<td>
元素。<td>
。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Random Images in Table</title>
<style>
td { width: 100px; height: 100px; border: 1px solid black; }
</style>
</head>
<body>
<table>
<tr>
<td id="cell1"></td>
<td id="cell2"></td>
<td id="cell3"></td>
</tr>
<tr>
<td id="cell4"></td>
<td id="cell5"></td>
<td id="cell6"></td>
</tr>
</table>
<script>
const images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg'];
const cells = document.querySelectorAll('td');
cells.forEach(cell => {
const randomIndex = Math.floor(Math.random() * images.length);
cell.style.backgroundImage = `url(${images[randomIndex]})`;
});
</script>
</body>
</html>
Set
来存储已经使用过的索引。const usedIndexes = new Set();
cells.forEach(cell => {
let randomIndex;
do {
randomIndex = Math.floor(Math.random() * images.length);
} while (usedIndexes.has(randomIndex));
usedIndexes.add(randomIndex);
cell.style.backgroundImage = `url(${images[randomIndex]})`;
});
<td>
。通过上述方法,可以有效防止随机生成的桌面镜像在同一个<td>
上重复生成,提升用户体验和应用性能。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云