【问题标题】:Toggle on/off buttons in Javascript在 Javascript 中切换开/关按钮
【发布时间】:2016-05-16 01:57:25
【问题描述】:

我被困住了。我有两个按钮,每个按钮都有一个功能,一个在单击时播放声音,一个在单击时暂停声音。我希望能够在它们之间切换,所以当它关闭时我只看到一个按钮说“声音开启”,反之亦然。 问题是:我的 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 中使用它,谢谢!

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

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

    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>

    【讨论】:

    • 这就是我想要的!虽然我希望按钮上的文本也可以根据点击的内容更改为关闭声音或开启声音,但知道我应该在那里做什么吗?
    • 完全按照我的方式工作,谢谢您的帮助
    猜你喜欢
    • 2017-02-06
    • 1970-01-01
    • 2012-03-22
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多