我想先在左侧生成五个图像 imgs,然后删除它的 lastchild 并将其余部分复制到右侧。如果用户单击左侧的额外 img,则清除所有并在左侧生成更多 5(10)个 img,并将 9 复制到右侧,依此类推。如果用户点击错误的地方,警告(“游戏结束”)。这是我的代码:
<html>
<head>
<style>
img{
position: absolute;
}
div{
position: absolute;
width: 500px;
height: 500px;
}
#rightSide { left: 500px;
border-left: 1px solid black;
}
</style>
<script>
var numberOfFaces = 5;
function generateFaces(){
var theLeftSide = document.getElementById("leftSide");
for (var i = 0; i < numberOfFaces; i++){
var img = document.createElement("img");
img.src = "smile.png";
var randomTop = Math.random() * 400;
var randomLeft = Math.random() * 400;
img.style.top = randomTop + "px";
img.style.left = randomLeft + "px";
theLeftSide.appendChild(img);
}
var theRightSide = document.getElementById("rightSide");
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
document.getElementById("rightSide").appendChild(leftSideImages);
var theBody = document.getElementByTagName("body")[0];
theLeftSide.lastChild.onclick = function nextLevel(event){
event.stopPropagation();
while (theBody.firstChild){
theBody.removeChild(theBody.firstChild);
}
numberOfFaces += 5;
generateFaces();
}
theBody.onclick = function gameover(){
alert("Game Over");
thBody.onclick = null;
theLeftSide.lastChild.onclick = null;
}
}
window.onload = generateFaces;
</script>
</head>
<body>
<h1>Matching Game</h1>
<p>click on the extra smiling face on the left</p>
<div id = "leftSide">
</div>
<div id = "rightSide">
</div>
</body>
</html>
我第一次可以生成和克隆,但是当我点击时没有任何反应,请问这是什么问题?
最佳答案
这可能是打字错误。
var theBody = document.getElementsByTagName("body")[0];
您的代码:var theBody = document.getElementByTagName("body")[0];
我建议为 html
使用一个好的编辑器。我用 Jetbrain phpStorm
修复了错误,但可能存在更好的错误。
关于javascript - 关于 onclick 的 Dom html javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45263032/