有一个图案游戏,当位置显示在左侧时,用户应该从右侧找到 1 张遗漏的图片,然后如果用户猜对了,他们将进入下一级别。
我的问题是,即使我点击了正确的图片,但在第一次迭代后出现错误选择的弹出窗口。
我尝试将 body
定义为初始子项,但无论选择正确还是错误,弹出窗口仍然显示。
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var theRightSide = document.getElementById("rightSide");
var theBody = document.getElementsByTagName("body")[0];
function generateFaces() {
for (var i = 0; i < numberOfFaces; i++) {
var createImg = document.createElement("IMG");
var randPositionTop = Math.floor(Math.random() * 400);
var randPositionleft = Math.floor(Math.random() * 400);
createImg.setAttribute("src", "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png");
createImg.style.top = randPositionTop + "px";
createImg.style.left = randPositionleft + "px";
theLeftSide.appendChild(createImg);
}
var leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
theRightSide.appendChild(leftSideImages);
theLeftSide.lastChild.onclick =
function nextLevel(event) {
event.stopPropagation;
numberOfFaces += 5;
alert("Next level!");
while (theLeftSide.firstChild) {
theLeftSide.removeChild(theLeftSide.firstChild);
}
generateFaces();
}
theBody.onclick =
function gameOver() {
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
alert("Game Over!");
};
}
#leftSide {
background-color: red;
position: absolute;
width: 500px;
height: 500px;
left: 50px;
}
#rightSide {
position: absolute;
left: 600px;
width: 500px;
height: 500px;
--border-left: solid 10px;
}
img {
position: absolute;
width: 50px;
height: 50px;
}
<link rel="stylesheet" href="style.css">
<body onload="generateFaces()">
<h3>Matching Game</h3>
<h5>Please choose missed smile !</h5>
<div id="leftSide">
</div>
<div id="rightSide">
</div>
<script src="jsCode.js"></script>
</body>
最佳答案
更新了你的 fiddle 。这是你想要的吗?
https://jsfiddle.net/ychq5rkm/12/
具体来说,它在 js 中使用 document.ready()
而不是在 html 中的 onload 中。正如评论中提到的那样,您需要实际调用 event.stopPropegation()
,因为它每次都持续到 body 并结束您的游戏。
关于javascript - 每个对象中的事件处理 onclick 正文响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38436415/