在Javascript中切换开/关按钮

时间:2016-05-15 17:31:08

标签: javascript jquery html

我被困住了。我有两个按钮,每个按钮都有一个功能,一个在点击时播放声音,另一个在点击时暂停声音。我希望能够在它们之间切换,所以我只看到一个按钮,当它关闭时说“声音开启”,反之亦然。 问题是:我的Javascript专有技术!

<audio id="spacesound"> </audio>
<button type="button" id="offbutton" class="offbutton" onclick="disableSound()">Sound off</button><br>
<button type="button" id="onbutton" class="onbutton" onclick="reenableSound()">Sound on</button>

这些是按钮,如有必要,还可以调用它们的功能。

//it plays on auto when the page is loaded
myAudiothree = new Audio('media/deepspace.mp3');
myAudiothree.loop = true;
myAudiothree.play();

//continue sound    
function reenableSound()
{
myAudiothree.play();
}

//pause sound
function disableSound()
{
myAudiothree.pause();
}

可能有一些CSS代码,但我宁愿在JS中使用它,谢谢!

1 个答案:

答案 0 :(得分:2)

解决方案很简单,“保存”变量中的实际状态......

var isPlaying=false;

function playOrPause()
{
  if(isPlaying)
  {
    myAudiothree.pause();
    isPlaying=false;
  }else
  {
    myAudiothree.play();
    isPlaying=true;
  }
}

现在你只有一个功能而不是两个。

编辑:

我为你创建了一个剪辑,用于展示如何更改按钮文本。

var isPlaying=false;

$('#myButton').click(function(){
    var $this = $(this);
  if(isPlaying)
    {
      isPlaying=false;
      $this.text('start'); 
      
      }else{
        isPlaying=true;
      $this.text('stop'); 
        }
                
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton">Play</button>