gpt4 book ai didi

javascript - 随机框生成器

转载 作者:行者123 更新时间:2023-11-30 14:18:22 25 4
gpt4 key购买 nike

我试图通过单击顶部和左侧位置为 0-400 的生成按钮,在现有的 div 中生成 100 个随机彩色框。此外,如果我将鼠标悬停在任何彩色框上,它会消失,直到最后一个会给我一个警报,最后一个框还剩下最后一个框。

我设法创建了一个生成不同颜色的框,但我不确定如何生成 100,更不用说将鼠标悬停在框上并在它出现时将其删除,应该怎么做?

我的 HTML:

<!doctype html>
<html lang="en">
<head>
<title> Generator </title>
<meta charset="utf-8">
<script src="prototype.js"></script>
<script src="task4.js"></script>
<style>
#container {
height: 500px;
}

p {
width: 70px;
height: 70px;
background-color: rgb(100, 100, 255);
border: solid 2px black;
position: absolute;
}
</style>
</head>
<body>
<div id="container">
</div>
<button id="myButton"
onclick="createBoxes()"> Generate More
</button>

</body>
</html>

我的JS

window.onload = function()
{
createBoxes();
}
function createBoxes()
{
var colors = ["red", "green", "blue", "purple", "yellow"];

var newP = document.createElement("p");
var top = 10 + "px";
var left = 10 + "px";
newP.style.top = top;
newP.style.left = left;
newP.style.backgroundColor = colors[ Math.floor( Math.random() *5 )];

$("container").appendChild(newP);
}
window.onload = function() {
createBoxes();

}

最佳答案

让我们一步步完成。

在创建盒子元素时,不应该使用p标签,div是最好的选择。

据我对你的问题的理解,我已经实现了。如果我遗漏了什么,请在评论中告诉我。

我在代码里添加了注释,看看你看懂没有。

window.onload = function() {
createBoxes();
}

function createBoxes() {
var left = 0;
var top = 0;
var colors = ["red", "green", "blue", "purple", "yellow"];
// create a for loop and run 99 times;
for (var i = 1; i < 100; i++) {
var newDiv = document.createElement("div");
newDiv.classList.add('box')
newDiv.style.backgroundColor = colors[Math.floor(Math.random() * 5)];
newDiv.style.top = top + 'px';
newDiv.style.left = left + 'px';
// now add the event on this one;
newDiv.addEventListener('mouseover', removeBoxes);
$("#container").append(newDiv);
left += 70; // increase left 70px each time in the loop
if (i % 5 == 0) { // if the we have 5 boxes in one row, reset left to 0px and increase top property by 70px to get another row;
left = 0;
top += 70;
}
}
}

// function to remove the boxes on hover;
function removeBoxes() {
$(this).remove();
}

// add the mouseover event listener;
$('div.box').on('mouseover', removeBoxes);
#container {
min-height: 200px;
}

div.box {
width: 70px;
height: 70px;
background-color: rgb(100, 100, 255);
border: solid 2px black;
display: inline-block;
position: absolute;
box-sizing: border-box;
}

#myButton {
position: absolute;
right: 0;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container">
</div>
<button id="myButton" onclick="createBoxes()"> Generate 99 More
</button>

关于javascript - 随机框生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53162168/

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