简体   繁体   中英

How can I animate an input range to change his value dynamically?

I have an HTML element input of type range:

<body onload="rotar()">
  <img src="#" id="locator" />
  <input type="range" name="points" id="loop" min="1" max="20" data-show-value="true">
</body>

it goes basically like this, this page shows images that change dynamically and I want that the slider id "loop" changes its value, just like the images so it moves according to it.

function rotar(){
var slider = document.getElementById("loop");
var locator = document.getElementById('locator'),
    dir = 'static/visor/img/',                   
    delayInSeconds = 3,                        
    num = 1,
    len = 20;
setInterval(function(){
    locator.src = dir + num+'.png';
    if (num === len){
        num = 1;
    }
    else{
        num++;
    }
    slider.value = num;
}, delayInSeconds * 50);}

I don't have any image dir so i just did it with an simple input. please check this http://jsfiddle.net/maxofpower/tAs6V/275/

<body onload="rotar()">
 <form ><div>
  <input id="loop" onchange="amount.value=rangeInput.value" oninput="amount.value=rangeInput.value" type="range" min="0" max="200" name="rangeInput" />
  <input id="box" type="text" value="0" name="amount" for="rangeInput"  oninput="rangeInput.value=amount.value" />
 </div></form>
</body>

<script>
 function rotar() {
 var slider = document.getElementById("loop");                             
  var num = 1;
  setInterval(function(){
  slider.value = num++;
  }, 500);
  };
</script>

Your issue is with the delay passed to the setInterval method, as the delay argument is in milliseconds, to get 2.8 seconds you'd have to multiply the delayInSeconds variable by 1000.

You had some mistakes in your code, you refreferenced the img#locator element with the variable name rotator the you used the variable name locator , which will cause an Undefined variable error. Im my answer I changed the variable's name from rotator to locator , also I made the delay to 2.8 seconds.

Here's a demo:

 function rotar() { var slider = document.getElementById("loop"), locator = document.getElementById('locator'), dir = 'static/visor/img/', delayInSeconds = 2.8, num = 1, len = 20; setInterval(function() { locator.src = dir + num + '.png'; num = (num === len) ? 1:num + 1; slider.value = num; }, delayInSeconds * 1000); } 
 <body onload="rotar()"> <img src="#" id="locator" /> <input type="range" name="points" id="loop" min="1" max="20" data-show-value="true"> </body> 

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