如何修复else语句未激活

时间:2019-07-08 00:43:21

标签: javascript html

我正在尝试为背景音频创建一个切换开关,并且某些else语句不起作用。

我尝试使用else / else if并以多种方式进行设置,但是似乎没有任何效果。

function toggle() 
{

    if (!play()) {
        play();
    }
         //HERE IS THE ONE NOT WORKING//
    else {
        mute();
    }
}


function play() 
{
    //Sound Icon
    document.getElementById('muteB').src = 'MuteOff.png';
    //Play Music
    document.getElementById('mplayer').innerHTML = ('<source src="GameTheme.mp3" type="audio/mp3">');
}

    //MUTE FUNCTION
function mute() 
{
    //Sound Off Icon
    document.getElementById('muteB').src = 'MuteOn.png';
    //Stop Music
    document.getElementById('mplayer').innerHTML = ('');
}

HTML

<img id="muteB" src="MuteOn.png" onclick="toggle()" />

我希望toggle()函数实际切换音频,但是我只能将其打开,而不是关闭。

1 个答案:

答案 0 :(得分:1)

您需要创建一个全局变量isPlaying,两个函数playmute中的更改都相应地发生

let isPlaying = false;

function toggle() {
    if (!isPlaying) {
        play();
    }
    //HERE IS THE ONE NOT WORKING//
    else {
        mute();
    }
}


function play() {
    //Sound Icon
    document.getElementById('muteB').src = 'MuteOff.png';
    //Play Music
    document.getElementById('mplayer').innerHTML = ('<source src="GameTheme.mp3" type="audio/mp3">');
    isPlaying = true;
}

//MUTE FUNCTION

function mute() {
    //Sound Off Icon
    document.getElementById('muteB').src = 'MuteOn.png';
    //Stop Music
    document.getElementById('mplayer').innerHTML = ('');
    isPlaying = false;
}