如何使用箭头键遍历< span> s [英] How to iterate through <span>s with Arrow keys
问题描述
我有几个跨度:
< span>项目1< / span>
< span>第2项< / span>
< span>第3项< / span>
这些项目全部紧挨着另一个。我希望用户按下箭头键(左&右)&然后移动跨度(在我的情况下,这将更新当前对象并分派一个动作)。
编辑:我没有任何示例代码,因为我是绝对的新人。但我也不希望任何人在这里发布一个工作解决方案,我只想给我一些一般性的建议,我将如何在React / Redux中从概念上解决这个问题。
以下是一个简单的JavaScript示例:
function move(dir){var selectables = Array.from(document.querySelectorAll('。selectable')); var selected = document.querySelector('。selected'); var i = selectables.indexOf(selected); i =(i + selectables.length + dir)%selectables.length; selected.classList.remove(选择); document.addEventListener('keydown',function(e){switch(e.which){case 37:return move(-1); case 39:return move (1);}});
.selected {background -color:yellow}
< span class =selectable项目1< / span>< span class =selectable>项目2< / span>< span class =selectable>项目3< / span>< p>按左/右箭头键
I have a few spans:
<span>Item 1</span>
<span>Item 2</span>
<span>Item 3</span>
The items are all next to another. I would like the user to press the arrow keys (left & right) & then move through the spans (in my case this would update the current object and dispatch an action).
Edit: I do not have any sample code, as I am an absolute beginner. But I also do not expect anyone to post a working solution here, I would just like to have some general advice how I would conceptually approach this in React/Redux.
Here is a plain JavaScript example:
function move(dir) {
var selectables = Array.from(document.querySelectorAll('.selectable'));
var selected = document.querySelector('.selected');
var i = selectables.indexOf(selected);
i = (i+selectables.length+dir)%selectables.length;
selected.classList.remove('selected');
selectables[i].classList.add('selected');
}
document.addEventListener('keydown', function (e) {
switch(e.which) {
case 37: return move(-1);
case 39: return move(1);
}
});
.selected { background-color: yellow }
<span class="selectable selected">Item 1</span>
<span class="selectable">Item 2</span>
<span class="selectable">Item 3</span>
<p>Set focus on this page and press left/right arrow keys
这篇关于如何使用箭头键遍历< span> s的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!