1 回答
TA贡献1860条经验 获得超8个赞
您不需要继续添加图像,而只需更改源
我还更改为 addEventListener 和 querySelector 因为它更优雅
document.getElementById("add").addEventListener("click",function() {
const value = parseInt(document.getElementById('id1').value, 10);
if (isNaN(value)) {
addDiv();
addDiv2();
addDiv3();
addbutterfly();
incrementValue();
} else {
incrementValue();
// Get the value of the "textfield"
const value = parseInt(document.getElementById('id1').value, 10);
// If the value is even, add "bfly2.gif", otherwhise add "bfly1.gif"
document.getElementById("bfly").src = value % 2 === 0 ? "bfly2.gif" : "bfly1.gif";
}
})
function addDiv() {
var div1 = document.createElement('div');
div1.classList.add('div1');
document.body.appendChild(div1);
}
function addDiv2() {
var div2 = document.createElement('div');
div2.classList.add('div2');
document.querySelector(".div1").appendChild(div2);
}
function addDiv3() {
var div3 = document.createElement('div');
div3.classList.add('div3');
document.querySelector(".div2").appendChild(div3);
}
function addbutterfly() {
var img = document.createElement('img');
img.id="bfly"
img.src = "bfly1.gif";
document.querySelector(".div3").appendChild(img);
}
function incrementValue() {
var value = parseInt(document.getElementById('id1').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('id1').value = value;
}
.div1 {
background-color: red;
margin: 1em;
height: 500px;
width: 500px;
justify-content: center;
align-items: center;
}
.div2 {
background-color: yellow;
height: 300px;
width: 300px;
}
.div3 {
background-color: limegreen;
height: 150px;
width: 150px;
}
div {
display: flex;
justify-content: center;
align-items: center;
position: relative;
}
<html>
<head>
<meta charset="utf-8">
<script src="bflyjs.js" defer></script>
</head>
<body>
<div class="button">
<button type="button" id="add">click to get nested divs</button>
<textarea id="id1"></textarea>
</div>
</body>
</html>
添加回答
举报