HTML Javascript change image with Slider bar step

雨燕双飞 提交于 2021-02-05 08:56:24

问题


<input id="valR" type="range" min="0" max="100" value="0" step="5" oninput="showVal(this.value)" onchange="showVal(this.value)" />
    <span id="range">0</span>
    <img id="img">

<script>

    var val = document.getElementById("valR").value;
        document.getElementById("range").innerHTML=val;
        document.getElementById("img").src = val + ".jpg";
        function showVal(newVal){
          document.getElementById("range").innerHTML=newVal;
          document.getElementById("img").src = newVal+ ".jpg";
        }
</script>

hi people, based on this code, I need to be able to load the range between 0 - 35 an image between 35 - 65 another image and 65 - 100 other.

thank you very much for your help


回答1:


I added if(newVal >= 0 && newVal < 35) with 2 conditions to check if value is in a range and then set <img>

You can't use document.getElementById("img").src = newVal+ ".jpg";, in that case you will get 100 different images

<input id="valR" type="range" min="0" max="100" value="0" step="5" oninput="showVal(this.value)" onchange="showVal(this.value)" />
    <span id="range">0</span>
    <img id="img">

<script>

    var val = document.getElementById("valR").value;
        document.getElementById("range").innerHTML=val;
        document.getElementById("img").src = val + ".jpg";
        function showVal(newVal){
          document.getElementById("range").innerHTML=newVal;
          if(newVal >= 0 && newVal < 35)
            document.getElementById("img").src = "first_image.jpg";
          else if(newVal >= 35 && newVal < 65)
            document.getElementById("img").src = "second_image.png";
          else if(newVal >= 35 && newVal < 65)
            document.getElementById("img").src = "third_image.png";
        }
</script>


来源:https://stackoverflow.com/questions/55401794/html-javascript-change-image-with-slider-bar-step

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!