简体   繁体   English

如何通过Javascript显示/隐藏一系列有序元素?

[英]How to show/hide a series of ordered elements by Javascript?

In a series of elements ordered by id numbers as 在按ID号排序的一系列元素中,

<div id="test-1">
<div id="test-2">
<div id="test-3">
<div id="test-4">
<div id="test-5">

Imagine that we want to show/hide each element by arrow keys. 假设我们要通过箭头键显示/隐藏每个元素。 What is the best way to do so in pure Javascript? 用纯Java脚本执行此操作的最佳方法是什么?

The question is when the first three elements are shown, how we can detect that back arrow show hide element #3 and forward arrow should show element #4 ? 问题是,当显示前三个元素时,如何检测后退箭头显示隐藏元素#3和前进箭头应显示元素#4

We need to keep track of the current div being shown and handle the keydown event to check for the left and right keys. 我们需要跟踪当前显示的div并处理keydown事件以检查左键和右键。 See my example below. 请参阅下面的示例。

jsFiddle 的jsfiddle

JavaScript JavaScript的

var numDivs = 5;

var divs = [];
for (var i = 1; i < numDivs + 1; i++)
    divs.push(document.getElementById('test-' + i));

var current = 0;
showDiv(current);

window.onkeydown = function (e) {
    if (e.keyCode == 37) { 
        // Left
        current--;
        if (current < 0)
            current = numDivs - 1; // wrap around back to max
        showDiv(current);
    } else if (e.keyCode == 39) {
        // Right
        current++;
        if (current == numDivs)
            current = 0; // wrap around back to 0
        showDiv(current);
    }
};

// Hide all divs except for index passed in
function showDiv(div) {
    for (var i = 0; i < divs.length; i++) {
        divs[i].style.display = div == i ? 'block' : 'none';
    }
}

CSS CSS

div {
    width:100px;
    height:100px;
    background-color:#F00;
    display:none;

    line-height:100px;
    font-size:4em;
    text-align:center;
}
div:nth-child(even) {
    background-color:#0F0;
}

Update 更新

If you weren't aware of the number of elements then I suggest you use a class to define the elements. 如果您不知道元素的数量,那么建议您使用一个类来定义元素。

HTML HTML

<div class="slide"></div>
<div class="slide"></div>
<div class="slide"></div>
<div class="slide"></div>

JS JS

All the javascript would be the same except for how you initialise divs and numDivs . 除了初始化divsnumDivs外,所有的javascript都是相同的。

var divs = document.getElementsByClassName('slide');
var numDivs = divs.length;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM