简体   繁体   中英

Change image SRC when input slider changed

I'm have a slider that goes from 1 - 3, I'd like my image src to change depending on what the slider is set to. I've tried to do this using an else if statement but it doesn't seem to be changing?

HTML

<span id="valBox"></span>
<input type="range" min="1" max="3" step="1">
<img id="demo" src="default-image.png">

Javascript

<script>
    if (step === 1) {
    document.querySelector("input.step").innerHTML.src = "one-image.png";
    } else if (step === 2) {
    document.querySelector("input.step").innerHTML.src = "two-image.png";
    }  else if (step === 3) {
    document.querySelector("input.step").innerHTML.src = "three-image.png";
    };
</script

You need to run your JavaScript in an onchange event handler.

 const imageElement = document.getElementById("demo"); const selectorElement = document.getElementById("selector"); selectorElement.onchange = () => { const step = selectorElement.valueAsNumber; if (step === 1) { imageElement.src = "one-image.png"; } else if (step === 2) { imageElement.src = "two-image.png"; } else if (step === 3) { imageElement.src = "three-image.png"; } }
 <span id="valBox"></span> <input id="selector" type="range" min="1" max="3" step="1"> <img id="demo" src="default-image.png">

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