当我单击任何块时,它会添加一个新类.is-selected。当我通过单击块获得焦点时,它工作正常。但是当我使用箭头键将焦点放在另一个块上时它不起作用。使用箭头键时如何获得焦点?
let getBlocks = document.querySelectorAll(".block");
getBlocks.forEach((single) => {
single.addEventListener("focus", () => {
//remove all activated class
getBlocks.forEach((x) => {
x.classList.remove("is-selected");
});
//add the class to this new focus block
single.classList.add("is-selected");
});
});
* {
box-sizing: border-box;
}
.root {
max-width: 600px;
margin: 1rem auto;
}
.root:focus,
.block:focus {
outline: 0;
}
.is-selected {
background-color: #f4f8ff !important;
border: 1px solid #deebff !important;
}
<div class="root" contenteditable>
<p name="jYdi0" class="block" tabindex="0">1</p>
<p name="Hdy89" class="block" tabindex="0">2</p>
<p name="wEldk" class="block" tabindex="0">3</p>
</div>
胡子哥哥
侃侃尔雅
相关分类