【问题标题】:Play a sound when the user clicks a button and then go to a different page当用户单击按钮然后转到其他页面时播放声音
【发布时间】:2020-12-02 14:45:56
【问题描述】:

目前有这个代码:

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <audio id="audio" src="D:\DiscordFAQ\baba.mp3" autostart="false" ></audio>
    <!--<a onclick="PlaySound()"> Play</a> -->
    <script>
    function PlaySound() {
          var sound = document.getElementById("audio");
          sound.play()
      }
    </script>
    
<button type="button" onclick="PlaySound(); location.href = 'Profielfotoaanpassen.html'">Volgend Onderwerp</button> 
  </body>

</html>

当用户单击按钮时,我需要它播放声音,当声音结束时,它需要转到不同的页面。

现在发生的情况是声音没有播放,因为它立即转到另一个页面。

【问题讨论】:

标签: javascript html button audio onclick


【解决方案1】:

您可以通过sound.duration 获得声音长度,并通过setTimeout() 延迟重定向。这是完整的代码:

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <audio id="audio" src="D:\DiscordFAQ\baba.mp3" autostart="false" ></audio>
    <!--<a onclick="PlaySound()"> Play</a> -->
    <script>
      function PlaySound() {
          var sound = document.getElementById("audio");
          sound.play();
          setTimeout(function(){ location.href = 'Profielfotoaanpassen.html'; }, sound.duration * 1000);
      }
    </script>
    
    <button type="button" onclick="PlaySound();">Volgend Onderwerp</button> 
  </body>

</html>

现场演示:https://stackoverflow-play-and-redirect.glitch.me/

【讨论】:

  • &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;script src="script.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;audio id="audio" src="Documents\testsite\baba.mp3" autostart="false" &gt;&lt;/audio&gt; &lt;script&gt; function PlaySound() { var sound = document.getElementById("audio"); sound.play(); setTimeout(function(){ location.href = 'Profielfotoaanpassen.html'; }, sound.duration * 1000); } &lt;/script&gt; &lt;button type="button" onclick="PlaySound();"&gt;Volgend Onderwerp&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; 不播放任何声音,只是转到其他页面。
  • 这很奇怪,对我来说它有效。试试this live demo。我希望它有所帮助。
猜你喜欢
  • 1970-01-01
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多