【发布时间】:2021-07-02 09:39:02
【问题描述】:
我在为一个画廊制作网站时遇到问题。 我为可以显示和隐藏多个图像的按钮编写了代码。 我打算让按钮可以随机放置几个图像。 我编写的代码只能用于一张图片。
请告诉我用作按钮以将多个图像放置在随机位置的代码。
- 用户可以通过按下按钮隐藏图像。
- 当用户再次按下按钮时,它会将图像放置在另一个随机位置。
const btn = document.querySelector("button");
const height = document.documentElement.clientHeight;
const width = document.documentElement.clientWidth;
const box = document.getElementById("color");
btn.addEventListener("click", () => {
let randY = Math.floor((Math.random() * height) + 1);
let randX = Math.floor((Math.random() * width) + 1);
box.style.top = randY + "px";
box.style.right = randX + "px";
});
function showhide() {
var x = document.querySelectorAll("#color");
var i;
for (i = 0; i < x.length; i++) {
if (x[i].style.display === "block") {
x[i].style.display = "none";
} else {
x[i].style.display =
"block";
}
}
}
body {
height: 500px;
}
.random {
position: absolute;
}
<button onclick="showhide()" value="Zeige Features" id="button">click me</button>
<img id="color" style="display: none;" class="random" src="http://lorempixel.com/200/200/">
<img id="color" style="display: none;" class="random" src="http://lorempixel.com/200/200/">
【问题讨论】:
-
必须是唯一的,所以如果你选择
document.getElementById(),你总是只能得到一个元素,如果你需要有多个元素,请为此使用类。 -
您已经包含了 JQuery,但没有在代码中使用任何 JQuery。所以我删除了它。
-
首先感谢您的评论。你能更详细地评论吗?我不是编码专家,所以我需要一个编码示例的评论。