gpt4 book ai didi

javascript - 添加兄弟 div 后更改 div 的样式

转载 作者:行者123 更新时间:2023-11-30 14:41:37 25 4
gpt4 key购买 nike

当我向#boundary div 添加同级div 时,我无法再更改#box 子div 的样式。我究竟做错了什么?以下是我的代码的简化版本:

let box = document.getElementById("box");
let boundary = document.getElementById("boundary")

//Adding this line prevents my code from changing the #box style to blue
boundary.innerHTML += "<div>A</div>"

document.addEventListener("keydown", function(event) {
if (event.key == "ArrowDown") {
box.style.backgroundColor = "blue"
}
})
#box {
width: 75px;
height: 75px;
background-color: green;
border: solid black 1px;
position: absolute;
top: 100px;
left: 100px;
}
<div id="boundary">
<div id="box"></div>
</div>

最佳答案

当您将一个新字符串附加到 innerHTML 时,就像您在 #boudary 中创建了一个新的 HTML 内容,因此您选择的旧元素与创建的新元素不同。

要验证这一点,请在 DOM 更改后选择您的元素,您将创建新的元素并能够更改其样式:

let boundary = document.getElementById("boundary")

boundary.innerHTML += "<div>A</div>";

//Here you select the new one
let box = document.getElementById("box");

document.addEventListener("click", function(event) {

box.style.backgroundColor = "blue"

})
#box {
width: 75px;
height: 75px;
background-color: green;
border: solid black 1px;
position: absolute;
top: 100px;
left: 100px;
}
<div id="boundary">
<div id="box"></div>
</div>

关于javascript - 添加兄弟 div 后更改 div 的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49565148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com