简体   繁体   English

切换Java中的开/关按钮

[英]Toggle on/off buttons in Javascript

I'm stuck. 我被卡住了。 I've got two buttons with each a single function, one that plays a sound when clicked and one that pauses the sound when clicked. 我有两个按钮,每个按钮都有一个功能,一个按钮在单击时播放声音,一个按钮在单击时暂停声音。 I want to be able toggle between them so I just see one button saying "Sound on" when it's off and vice versa. 我希望能够在它们之间切换,所以我只看到一个按钮,当它关闭时会说“ Sound on”,反之亦然。 Problem is: my Javascript knowhow! 问题是:我的Java技术诀窍!

<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>

These are the buttons, and in case if necessary, the functions they call. 这些是按钮,在必要时调用它们的功能。

//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();
}

There might be some CSS code for this but I'd much rather have it in JS, thank you! 可能会有一些CSS代码,但是我宁愿在JS中使用它,谢谢!

The solution is simple "save" the actual state in a variable... 解决的方法是简单地将实际状态“保存”到变量中。

var isPlaying=false;

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

now you only have one function instead of two. 现在您只有一个功能,而不是两个。

Edit: 编辑:

I created a snipped for you, for showing how to change the button text also. 我为您创建了一个片段,用于显示如何更改按钮文本。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM