gpt4 book ai didi

javascript - 我想单击一个按钮并在我的容器中的随机位置出现一个随机图像

转载 作者:行者123 更新时间:2023-11-28 02:03:18 25 4
gpt4 key购买 nike

我希望能够在您每次单击底部的“尝试”按钮时在随机位置出现随机图像。 我已经能够让它随机化图像,但我很难让随机位置也适用于随机化的图像。

<input id="input" type="text" placeholder="Enter a background colour...">

<button>enter</button>

<div id="container">
<img id="picture" src="img/img1.jpg">
</div>

<button onclick="randAll();" id = "randomButton">Try!</button>


<script>
var bColour = document.getElementById("container");
var button = document.querySelector("button");
button.addEventListener("click", clickHandler, false);
button.style.cursor = "pointer";

function clickHandler()
{
var input = document.querySelector("#input");
bColour.style.backgroundColor = input.value;
}

var pix = new Array("img/img1.jpg", "img/img2.jpg", "img/img3.jpg", "img/img4.jpg");

function choosePic() {
var randomNum = Math.floor(Math.random() * pix.length);
document.getElementById("picture").src = pix[randomNum]

}

function randPos() {
Math.floor(Math.random() * 700);


}


</script>

最佳答案

像这样应用一些 CSS:

#picture {
position: absolute;
}

#container {
width: 750px;
height: 100px;
}

然后:

function randPos() {
var x = Math.floor(Math.random() * 700);
document.getElementById("picture").style.left = x + 'px';
}

根据需要调整我选择的具体宽度和高度。

关于javascript - 我想单击一个按钮并在我的容器中的随机位置出现一个随机图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49184443/

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