Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 对当前关注的元素使用appendChild_Javascript - Fatal编程技术网

Javascript 对当前关注的元素使用appendChild

Javascript 对当前关注的元素使用appendChild,javascript,Javascript,考虑以下代码: console.log('New node') var节点=document.createElement(“div”); node.appendChild(document.createTextNode(“+”); document.getElementById(“elem”).appendChild(节点) + 您需要在div上设置tab index以使其可聚焦,但随后您可以侦听聚焦事件并存储最后聚焦的元素。您需要手动存储当前项目,而不是依赖document.activeE

考虑以下代码:

console.log('New node')
var节点=document.createElement(“div”);
node.appendChild(document.createTextNode(“+”);
document.getElementById(“elem”).appendChild(节点)

+

您需要在div上设置tab index以使其可聚焦,但随后您可以侦听聚焦事件并存储最后聚焦的元素。您需要手动存储当前项目,而不是依赖
document.activeElement
获取最后一个焦点元素,因为这将更改为您正在单击的按钮

const appendbtn=document.querySelector(“#appendit”);
const addbtn=document.querySelector(“#addbox”);
让activeElement=null;
设计数器=0;
appendbtn.addEventListener('click',function(){
if(activeElement){
const node=document.createElement('span');
node.textContent='>';
appendChild(节点);
}
});
addbtn.addEventListener('click',function(){
const text=document.createElement('span');
text.textContent='Box'+(计数器++);
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');
});
框。追加子项(文本);
const container=document.querySelector('.box');
容器.附件(盒);
});
.box{
边框:1px实心#ddd;
边界半径:4px;
保证金:1rem;
填充:1rem;
}
.box.selected{
背景色:#f9f9f9;
}

添加框
附加V形

非常感谢您的帮助。我不想依赖于点击,但是对于任何被移动的元素(比如说带有标签,或者如果它是刚创建的),它不需要点击,你可以设置
activeElement
为任何你喜欢的,从任何你想要的事件?那么我的错,我不理解代码。此外,代码段也不能正确运行,这只适用于活动的单击,而不适用于焦点(例如,按TAB键,此时元素不是activeElement,而是onfocus)。好的,您可以在任何项目上侦听焦点事件,您可能可以将其连接到自定义元素,并将activeElement设置为获得焦点的元素。这就是为什么我提到可以在另一个事件中设置它,因为单击可能不适合您的情况。