使用 JavaScript 在页面加载时播放声音 [英] Play a sound on page load using JavaScript

查看:97
本文介绍了使用 JavaScript 在页面加载时播放声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在使用 JavaScript 触发 onload 事件时播放声音文件?

How can I play a sound file when the onload event fires using JavaScript?

如果我有一个网页,当用户点击一个按钮时会弹出一个窗口.加载弹出窗口时,页面会播放声音文件.

If I have a webpage, when a user clicks on a button and this will pop-up a window. While the pop-up window is loading, the page will play a sound file.

推荐答案

将 HTML5 音频元素添加到您的文档中:

Add a HTML5 audio element into your document:

 <audio id="foobar" src="yoursample.ogg" preload="auto"> 

通过 CSS 将其设置为隐藏:

Set it hidden via CSS:

 #foobar { display: none }

在任何 JavaScript 事件处理程序上播放音频:

On the any JavaScript event handler play the audio:

var sample = document.getElementById("foobar");
sample.play();

了解更多信息

https://developer.mozilla.org/en-US/docs/Using_HTML5_audio_and_video

根据您的 Web 应用程序用途,您可能希望支持旧浏览器:

Depending on your web application purpose you might want to support old browsers:

http://www.misfitgeek.com/play-sound-in-html5-and-cross-browser-support-with-backward-compatability/

这篇关于使用 JavaScript 在页面加载时播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆