2017-04-11 362 views
0

我有4个孩子像这样的HTML DOM元素:显示/隐藏DOM元素

<div id="container> 
    <img class="hide> 
    <img class="hide> 
    <img class="hide> 
    <img class="hide> 
</div> 

我有一个这样的输入范围的元素:

<input id="input_range type="range" min="1" max="4" value="1"> 

我根据输入范围值想要显示/隐藏img元素。

例如:如果输入值当前是3,我想通过切换CSS类来显示第一个,第二个和第三个img,并隐藏第四个img

如何做到这一点与香草的Javascript?

这里是我当前的脚本:

var input_range = document.getElementById('input_range'); 
var scene = document.getElementById('container'); 

input_range.addEventListener('input', function(){ 
    hideElements(container, this.value); 
}) 

function hideElements(parent_element, number_of_children){ 
    var children = parent_element.children; 
    for (left = 0; left < number_of_children; ++left) { 
     children[left].classList.remove('hide'); 
    } 

} 

此代码去除CSS隐藏类。但是如何根据输入值将课程退回?

非常感谢。

+1

请问你的脚本是什么样子? – Rayon

+0

我编辑了我的第一篇文章,并添加了我当前的脚本。 – Ache

+0

这将是很好,如果你可以添加代码作为js片段 – radbrawler

回答

2

你能像这样工作

var input_range = document.getElementById('input_range'); 
var scene = document.getElementById('container'); 

input_range.addEventListener('input', function(){ 
    hideElements(container, this.value); 
}) 

function hideElements(parent_element, number_of_children){ 
    var children = parent_element.children; 
    for (left = 0; left < children.length; ++left) { 
     if (left < number_of_children) { 
      children[left].classList.remove('hide'); 
     } else { 
      children[left].classList.add('hide'); 
     } 
    } 

} 
+1

你的摇滚radbrawler。问题解决了。 – Ache

1

下面是一个使用自定义的原型另一种方式:http://codepen.io/anon/pen/mmbeWw

请注意,我用的div而不只是这样我就可以显示输出。

HTML:

<input id="input_range" type="range" min="1" max="4" value="1"> 
<div id="container"> 
    <div class="hide">1</div> 
    <div class="hide">2</div> 
    <div class="hide">3</div> 
    <div class="hide">4</div> 
</div> 

CSS:

.hide { 
    display: none; 
} 

JS:

var input_range = document.getElementById('input_range'); 
var scene = document.getElementById('container'); 

input_range.addEventListener('input', function(){ 
    scene.elementRange(this.value, 'hide', 'show'); 
    scene.elementRange(this.value, 'show', 'hide'); 
}); 

Node.prototype.elementRange = function(range, newClass, oldClass){ 
    for (var i = 0; i < this.children.length; i++) { 
    this.children[i].classList.add(oldClass); 
    } 

    for (var i = 0; i < range; i++) { 
    this.children[i].classList.remove(oldClass); 
    this.children[i].classList.add(newClass); 
    } 
} 
+0

谢谢adamj!有趣的建筑,值得研究。 – Ache