Audio autoplay 属性
查看音频在加载后是否设置了立即播放:
<audio id="myAudio" controls autoplay>
<source src="/examples/horse.ogg" type="audio/ogg">
<source src="/examples/horse.mp3" type="audio/mpeg">
您的浏览器不支持 audio 元素。
</audio>
<p>查看音频在加载后是否设置了立即播放。</p>
<p id="demo"></p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction() {
var x = document.getElementById("myAudio").autoplay;
document.getElementById("demo").innerHTML = x;
}
</script>
定义和用法
autoplay 属性设置或返回音视频是否在加载后即开始播放。
该属性反映了 <audio> autoplay 属性。
如果设置了autoplay 属性,则指定音频在加载后立即播放。
注意: <audio> 元素是 HTML5 中新元素。
浏览器支持
![]()
![]()
![]()
![]()
![]()
The autoplay property 所有主流浏览器都支持
注意: Internet Explorer 8 及更早IE版本不支持 <video> 元素。
语法
返回 autoplay 属性:
audioObject.autoplay
设置 autoplay 属性:
audioObject.autoplay = true | false
属性值
| 值 | 描述 |
|---|---|
| true|false | 设置音视频是否在加载后即开始播放。
|
技术细节
| 返回值: | 布尔值,如果设置了音频自动播放返回 true,否则返回 false。 |
|---|---|
| 默认值: | false |
更多实例
启用自动播放,并重新加载视频:
<audio id="myAudio" controls>
<source src="/examples/horse.ogg" type="audio/ogg">
<source src="/examples/horse.mp3" type="audio/mpeg">
你的浏览器不支持audio元素。
</audio><br>
<button onclick="enableAutoplay()" type="button">启用 autoplay</button>
<button onclick="disableAutoplay()" type="button">禁用 autoplay</button>
<button onclick="checkAutoplay()" type="button">检查 autoplay 状态</button>
<script>
var x = document.getElementById("myAudio");
function enableAutoplay() {
x.autoplay = true;
x.load();
}
function disableAutoplay() {
x.autoplay = false;
x.load();
}
function checkAutoplay() {
alert(x.autoplay);
}
</script>
以下实例演示了如何创建 <video> 元素及设置 autoplay 属性:
<p>点击按钮创建AUDIO 元素, 一个设置了 autoplay 为 true, 另外一个设置了 autoplay 为 false。</p>
<button onclick="myFunction(true)"> Audio 设置 autoplay</button>
<button onclick="myFunction(false)">Audio 不设置 autoplay</button>
<br>
<script>
function myFunction(p) {
var x = document.createElement("AUDIO");
x.setAttribute("id", "myVideo");
x.setAttribute("controls", "controls");
var y = document.createElement("SOURCE");
y.setAttribute("src", "/examples/horse.ogg");
y.setAttribute("type", "audio/ogg");
x.appendChild(y);
var z = document.createElement("SOURCE");
z.setAttribute("src", "/examples/horse.mp3");
z.setAttribute("type", "audio/mpeg");
x.appendChild(z);
// 设置 autoplay 属性:
x.autoplay = p;
document.body.appendChild(x);
}
</script>
相关页面
HTML 参考手册: HTML <audio> autoplay 属性
Audio 对象
Audio 对象