[英]How to make sound when a <a> or <button> is clicked in JS
How can I make a sound ("MySound.mp3") hidden in the background when a <a>
element or <button>
element with the id "click_sound" is clicked in JavaScript, is it possible? 当在JavaScript中单击带有id“click_sound”的
<a>
元素或<button>
元素时,如何在背景中隐藏声音(“MySound.mp3”),是否可能?
Remember I want to make a sound in the background if an <a>
or <button>
are clicked! 请记住,如果单击
<a>
或<button>
,我想在后台发出声音!
The Code: 编码:
<html>
<head></head>
<body>
<a id="click_sound">Click me</a>
<button id="click_sound">Click me</button>
</body>
</html>
The sound file name: 声音文件名:
MySound.mp3 MySound.mp3
The easiest way to do what you are asking is to play the audio using javascript, when the button
or a
(or really any) tag is clicked. 做你所要求的最简单的方法就是打使用javascript音频上,当
button
或a
(或任何真正的)标签被点击。 There are a few ways you could do this: 有几种方法可以做到这一点:
You could run the javascript in an onmouseup
element: 您可以在
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>
or better yet, not run the audio constructor every time: 或者更好的是,不是每次都运行音频构造函数:
<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>
If you want to use an external script (either because you have other javascript, or you just prefer it that way, which I personally do) simply put it on the window
object: 如果你想使用一个外部脚本(因为你有其他的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: somefile.js:
window.audio = new Audio('./path_to_audio/sound.mp3')
Please let me know if you need any more information about any of the above. 如果您需要有关上述任何内容的更多信息,请与我们联系。
Note: You could also use: 注意:您还可以使用:
document.getElementById('click_sound').addEventListener('mouseup', () => new Audio('path_to_audio_file.mp3').play())
To achieve the same thing. 实现同样的目标。
For more information refer to this and this or look up "javascript 'Audio' constructor" and "onmouseup event". 欲了解更多信息,请参阅本和本或查找“JavaScript的‘音频’构造”和“onmouseup事件”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.