JS中点击<a>或<button>时如何发出声音
How to make sound when a <a> or <button> is clicked in JS
当在 JavaScript,有可能吗?
请记住,如果单击 <a>
或 <button>
,我想在背景中发出声音!
代码:
<html>
<head></head>
<body>
<a id="click_sound">Click me</a>
<button id="click_sound">Click me</button>
</body>
</html>
声音文件名:
我的声音.mp3
完成您要求的最简单方法是在单击 button
或 a
(或任何)标签时使用 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())
实现同样的目标。
有关详细信息,请参阅 this and this 或查找 "javascript 'Audio' constructor" 和 "onmouseup event"。
当在 JavaScript,有可能吗?
请记住,如果单击 <a>
或 <button>
,我想在背景中发出声音!
代码:
<html>
<head></head>
<body>
<a id="click_sound">Click me</a>
<button id="click_sound">Click me</button>
</body>
</html>
声音文件名:
我的声音.mp3
完成您要求的最简单方法是在单击 button
或 a
(或任何)标签时使用 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())
实现同样的目标。
有关详细信息,请参阅 this and this 或查找 "javascript 'Audio' constructor" 和 "onmouseup event"。