gpt4 book ai didi

javascript - Vanilla js 当上下按键时,更改事件类

转载 作者:行者123 更新时间:2023-12-02 02:02:12 25 4
gpt4 key购买 nike

当我按向上和向下键时,我希望更改所选的“div”元素。我怎样才能做到这一点。按键盘上的向下键,选择需要到最后一行。

document.addEventListener("DOMContentLoaded", function(event) { // <-- add this wrapper
var element = document.querySelectorAll('.element');

if (element) {

element.forEach(function(el, key){

el.addEventListener('click', function () {
console.log(key);

el.classList.toggle("active");

element.forEach(function(ell, els){
if(key !== els) {
ell.classList.remove('active');
}
console.log(els);
});
});
});
}
});
.element{
background: gray;
width:200px;
padding:10px;
margin-bottom:1px;
}

.element.active{
background: red;
}
<section>
<div class="element">BOX</div>
<div class="element">BOX</div>
<div class="element">BOX</div>
<div class="element">BOX</div>
<div class="element">BOX</div>
<div class="element">BOX</div>
</section>

最佳答案

将数组长度传递给监听器函数。如果您让该函数返回一个新函数(闭包),您可以记下当前元素索引,并将其与 0 或数组的长度进行比较。而且因为您保留了当前索引的记录,所以不需要遍历所有元素来删除事件类,只需从您所在的元素中删除该类,然后将其添加到下一篇。

// Grab all the elements
var elements = document.querySelectorAll('.element');

// Call a function as a key press handler that returns
// a new function (the actual listener)
// that deals with the key presses. We do this
// because we want to keep a variable `index` to identify which
// element in the collection we're on, and a closure
// (a function that hangs on to its local lexical environment
// when it's returned) is very convenient
document.addEventListener('keydown', handler(elements.length - 1), false);

// Set the initial element
elements[0].classList.add('active');

// So this is the handler that returns the closure.
// We pass in the array length, set up the index variable,
// and return a new listener function that deals with the key presses
function handler(arrayLength) {

let index = 0;

return function(e) {

if (e.code === 'ArrowUp' && index > 0) {
elements[index].classList.remove('active');
--index;
elements[index].classList.add('active');
}

if (e.code === 'ArrowDown' && index < arrayLength) {
elements[index].classList.remove('active');
++index;
elements[index].classList.add('active');
}

}

};
.element { background: gray; width: 200px; padding: 10px; margin-bottom: 1px; }
.active { background: red; }
<section>
<div class="element">BOX</div>
<div class="element">BOX</div>
<div class="element">BOX</div>
<div class="element">BOX</div>
<div class="element">BOX</div>
<div class="element">BOX</div>
</section>

其他文档

关于javascript - Vanilla js 当上下按键时,更改事件类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68860819/

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