【发布时间】:2021-11-30 03:00:41
【问题描述】:
-
我实际上是在尝试创建一个游戏,当有人将鼠标悬停在灰色区域时,它会询问他是否想玩,如果他确认然后随机 5 个 div 将出现在该父 div 的某个不同区域。
-
起初应该只有 1 个大 div。当有人将鼠标悬停时,如果他想玩游戏,就会有选项。然后大 div 将在其中生成 5 个小 div。 (接下来如果有人点击小div并需要跟踪点,我会删除,所以这是一个小游戏,仅供我学习使用
-
但我卡在这里是因为我无法在随机位置生成 div。如果你运行我的代码,当你确认播放时,你会看到 3 个 div 垂直出现
function hoverinside(x) {
let answer = confirm("Do you want to play the game?");
if (answer == true) {
alert("Enjoy the game");
myFunction();
}
else {
alert("If you want to play just hover on the gray area again");
location.reload();
}
}
function myFunction() {
var element = document.createElement('div');
element.style.cssText = "width:55px; height:55px; background:green;";
document.body.appendChild(element);
var div1 = document.getElementById("square");
div1.insertBefore(element, div1.childNodes[5])
var element2 = document.createElement('div');
element2.style.cssText = "width:55px; height:55px; background:yellow;"
document.body.appendChild(element2);
var div2 = document.getElementById("square");
div2.insertBefore(element2, div2.childNodes[5])
var element3 = document.createElement('div');
element3.style.cssText = "width:55px; height:55px; background:red;";
document.body.appendChild(element3);
var div3 = document.getElementById("square");
div3.insertBefore(element3, div3.childNodes[5])
}
function removediv1() {
var element = document.getElementById("div2");
element.classList.remove("div2");
}
h1 {
font-style: bold;
color: brown;
}
#square{
height: 350px;
width: 700px;
background-color: rgb(170, 168, 168);
border: brown;
border-style: solid;
}
#square1{
height: 35px;
width: 70px;
background-color: rgb(245, 10, 10);
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet" type="text/css">
<script src="gamejs.js"></script>
<title>Game</title>
</head>
<body onload=OpenInNewtab(google.com)>
<h1>Game:</h1>
<p>we will create the game over here. no problem just wait and chill and play with us.we will create the game over here. no problem just wait and chill and play with us.</p>
<h1>Points:</h1>
<br>
<div id="square" onmouseover="hoverinside(this)" >
<div id="child1"> </div>
</div>
</body>
</html>
这是我的代码
【问题讨论】:
-
你能澄清一下吗?您的意思是 5
divs 将出现在父 div 内,但在随机位置? -
您好,我已经添加了我的代码。我需要更改的地方请提及是否有人可以提供帮助非常感谢您
标签: javascript dom-events