在Javascript中切换开/关按钮 [英] Toggle on/off buttons in Javascript
问题描述
我被困住了.我有两个按钮,每个按钮都有一个功能,一个按钮在单击时播放声音,一个按钮在单击时暂停声音.我希望能够在它们之间切换,所以我只看到一个按钮,它在关闭时显示"Sound on",反之亦然. 问题是:我的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. Problem is: my Javascript knowhow!
<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();
}
可能有一些CSS代码,但是我宁愿在JS中使用它,谢谢!
There might be some CSS code for this but I'd much rather have it in JS, thank you!
推荐答案
解决方案很简单,就是将实际状态保存在变量中.
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.
我为您创建了一个片段,用于显示如何更改按钮文本.
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>
这篇关于在Javascript中切换开/关按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!