【问题标题】:How to make sound when a <a> or <button> is clicked in JS在 JS 中单击 <a> 或 <button> 时如何发出声音
【发布时间】:2019-10-24 09:34:56
【问题描述】:

当在 JavaScript 中单击 ID 为“click_sound”的&lt;a&gt; 元素或&lt;button&gt; 元素时,如何在背景中隐藏声音(“MySound.mp3”),可以吗?

请记住,如果单击 &lt;a&gt;&lt;button&gt;,我想在背景中发出声音!

代码:

<html>
  <head></head>
  <body>
    <a id="click_sound">Click me</a>
  <button id="click_sound">Click me</button>
  </body>
</html>

声音文件名:
我的声音.mp3

【问题讨论】:

标签: javascript html html5-audio


【解决方案1】:

buttona(或任何一个)标签被点击时,最简单的方法就是使用javascript 播放音频。有几种方法可以做到这一点:

您可以在 onmouseup 元素中运行 javascript:

<html>
  <head></head>
  <body>
    <a id="click_sound" onmouseup="new Audio('path_to_audio_file.mp3').play()">Click me</a>
    <button id="click_sound" onmouseup="new Audio('path_to_audio_file.mp3').play()">Click me</button>
  </body>
</html>

或者更好的是,不要每次都运行音频构造函数:

<html>
  <head></head>
  <body>
    <a id="click_sound" onmouseup="audio.play()">Click me</a>
    <button id="click_sound" onmouseup="audio.play()">Click me</button>

      <script>const audio = new Audio('path_to_audio_file.mp3')</script>
  </body>
</html>

如果您想使用外部脚本(或者因为您有其他 javascript,或者您只是更喜欢这种方式,我个人就是这样做的)只需将其放在 window 对象上:

<html>
  <head></head>
  <body>
    <a id="click_sound" onmouseup="window.audio.play()">Click me</a>
    <button id="click_sound" onmouseup="window.audio.play()">Click me</button>

      <script src='./path_to_file/somefile.js'></script>
  </body>
</html>

somefile.js:

  window.audio = new Audio('./path_to_audio/sound.mp3')

如果您需要有关上述任何内容的更多信息,请告诉我。

注意: 你也可以使用:

document.getElementById('click_sound').addEventListener('mouseup', () =>  new Audio('path_to_audio_file.mp3').play())

为了达到同样的目的。

有关更多信息,请参阅thisthis 或查找“javascript 'Audio' 构造函数”和“onmouseup 事件”。

【讨论】:

  • 没问题@adel 3.
猜你喜欢
  • 1970-01-01
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2016-07-11
  • 2023-02-03
相关资源
最近更新 更多