简体   繁体   中英

Show/hide DOM elements according to input range value

I have an HTML DOM element with 4 children like this:

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

And I have an input range element like this:

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

I want to show/hide the img elements according to the input range value.

For example: if the input value is currently 3, I want to show the 1st, 2nd and 3rd img , and hide the 4th img by toggling CSS classes.

How to do that with vanilla Javascript?

Here is my current script:

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');
    }

}

This code works for removing the CSS hide class. But how to put the class back according to the input value?

Thank you very much.

You can work like this

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');
        }
    }

}

Here's another way using a custom prototype: http://codepen.io/anon/pen/mmbeWw

Please note, I've used divs instead just so I could display the output.

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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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