尝试删除“leftSideImages”的最后一个子项,以使右侧的图像少于左侧的图像。下面是我的代码。目的是将左侧的图像克隆到右侧的负号上。谢谢!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Matching Game</title>
<style>
div {
position: absolute;
width: 500px;
height: 500px
}
img {
position: absolute
}
#rightSide {
left: 500px;
border-left: 1px solid black
}
</style>
<script>
function generateFaces(){
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var theRightSide = document.getElementById("rightSide");
for ( var i = 0; i< numberOfFaces; i++){
var random_top = Math.floor(Math.random() * 400);
var random_left = Math.floor(Math.random() * 400);
var img = document.createElement("img");
img.src="smile.png";
img.style.top = random_top + "px";
img.style.left = random_left + "px";
theLeftSide.appendChild(img);
}
var leftSideImages = theLeftSide.cloneNode(true);
//this doesn't work leftSideImages.removeChild(theLeftSide.lastChild);
// it gets rid of everything.
// I'm trying to clone the left side onto the right with one less image
theRightSide.appendChild(leftSideImages);
}
</script>
</head>
<body>
<h3>Matching Game</h3>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
<script>generateFaces()</script>
</body>
</html>
最佳答案
您需要使用removeChild和lastElementChild,如下所示:
var parent = document.getElementById("leftSide");
parent.removeChild(parent.lastElementChild);
<div id="leftSide">
<div>1</div>
<div>2</div>
<div>3</div>
</div>