简体   繁体   中英

multiple statements else if not working

I'm trying to replace a volume image when the player's volume level changes,
but with this code, the second else if does not work,
and the 3° image (VOL-1.png) does not appears...

All the other images (VOL-off, VOL-2, VOL-on) appear properly...

var myVideo1 = document.getElementById('myVideo1');
var bttnMuteUnmute = document.getElementById("bottoncinoMuteUnmute_myVideo1");

myVideo1.addEventListener("volumechange", function () {
    if (myVideo1.muted || myVideo1.volume <= 0.009) {
        bttnMuteUnmute.style.backgroundImage = "url(buttons-VOL-off.png)";
    } else if (myVideo1.volume <= 0.65) {
        bttnMuteUnmute.style.backgroundImage = "url(buttons-VOL-2.png)";
    } else if (myVideo1.volume <= 0.4) {
        bttnMuteUnmute.style.backgroundImage = "url(buttons-VOL-1.png)";
    } else {
        bttnMuteUnmute.style.backgroundImage = "url(buttons-VOL-on.png)";
    }
}, false);

What I'm doing wrong?

Any number which is lesser than 0.4 will also be lesser than 0.65 . So, when the number is lesser than 0.4 , it compares against <= 0.65 , it is Truthy, so displays VOL-2 picture.

So, you just have to change the order of the conditions, like this

...
} else if (myVideo1.volume <= 0.4) {
bttnMuteUnmute.style.backgroundImage = "url(buttons-VOL-1.png)";
} else if (myVideo1.volume <= 0.65) {
bttnMuteUnmute.style.backgroundImage = "url(buttons-VOL-2.png)";
} else {
...

Since if-else statements are evaluated in order, it gets stuck in VOL-2 because any option for VOL-1 also meets VOL-2. If you were to switch the order of VOL-1 and VOL-2, it should work.

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