简体   繁体   English

静音/取消静音按钮可发出背景声音

[英]Mute/unmute button for background sound

guys. 家伙。 Please explain this to me. 请给我解释一下。 I wanted to create a single mute/unmute button for my page. 我想为我的页面创建一个静音/取消静音按钮。 (audio starts automatically) So here the code I used first time: (音频会自动启动)因此,这里是我第一次使用的代码:

 <script> var sound = getElementById ('background_sound'); function mute(){ if(background_audio.muted == false){ background_audio.muted = true; } else { background_audio.muted = false; } } </script> 

But it didn't work. 但这没有用。 So I just removed the first line (I mean this var) and addressed the id directly. 因此,我只是删除了第一行(我的意思是这个变量)并直接解决了ID。 And it worked. 而且有效。 Now my html looks like this: 现在我的html看起来像这样:

 <audio id="background_audio" autoplay="true" loop="loop"> <source src="Audio/flute.mp3"> If you are reading this, it is because your browser does not support the audio element. </audio> <button onclick="mute()"> <i class="fa fa-music"></i></button> 

And javascript like this 和这样的javascript

 <script> function mute(){ if(background_audio.muted == false){ background_audio.muted = true; } else { background_audio.muted = false; } } </script> 

The question is how can I address Id directly without creating a variable? 问题是如何在不创建变量的情况下直接寻址ID? It works fine though but will I have any problems with the code later? 虽然可以正常工作,但是以后我的代码有问题吗? I just thought I need to assign a var this to work. 我只是认为我需要分配一个var来工作。 A bit confused. 有点困惑。

try this i am sure this will work 试试这个,我相信这会起作用

 <script>

            function mute(){
              if(document.getElementById('background_audio').muted == false){
                document.getElementById('background_audio').muted = true;
              } else {
                document.getElementById('background_audio').muted = false;
              }

    }
    </script>

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

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