gpt4 book ai didi

javascript - 使用 appendChild 到当前聚焦的元素

转载 作者:行者123 更新时间:2023-11-30 19:22:02 24 4
gpt4 key购买 nike

考虑这段代码:

console.log('New node')
var node = document.createElement("div");
node.appendChild(document.createTextNode("+"));
document.getElementById("elem").appendChild(node);
    <!DOCTYPE html>
<html>
<body>
<div id="elem">+</div>
</body>
</html>

因此,当前添加 "+" 作为新 div 的文本。

假设我想将另一个带有文本 ">" 的子 div 添加到用户查看 index.html 当前关注的任何 div,考虑到他选择的选项动态创建的 div,我该如何实现?

最佳答案

您需要在 div 上设置选项卡索引以使其可聚焦,然后您可以监听焦点事件并存储最后一个聚焦的元素。您需要手动存储当前项目,而不是依赖 document.activeElement 来获取最后一个聚焦元素,因为它会更改为您正在单击的按钮。

const appendbtn = document.querySelector('#appendit');
const addbtn = document.querySelector('#addbox');
let activeElement = null;
let counter = 0;
appendbtn.addEventListener('click', function() {
if (activeElement) {
const node = document.createElement('span');
node.textContent = '>';
activeElement.appendChild(node);
}
});
addbtn.addEventListener('click', function() {
const text = document.createElement('span');
text.textContent = 'Box ' + (counter++);

const box = document.createElement('div');
box.tabIndex = 0;
box.classList.add('box');
box.addEventListener('focus', function() {
if (activeElement) {
activeElement.classList.remove('selected');
}
activeElement = box;
activeElement.classList.add('selected');
});
box.appendChild(text);

const container = document.querySelector('.boxes');
container.appendChild(box);
});
.box {
border: 1px solid #ddd;
border-radius: 4px;
margin: 1rem;
padding: 1rem;
}

.box.selected {
background-color: #f9f9f9;
}
<div class="boxes">
</div>
<button id="addbox">
Add box
</button>
<button id="appendit">
Append chevron
</button>

关于javascript - 使用 appendChild 到当前聚焦的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57340043/

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