仅当存在外部样式表时,通过javascript添加HTML5音频源才起作用

问题描述 投票:0回答:1

我正在通过javascript添加音频源:

<audio id="audiotest" preload="none" controls volume=".2">
  <source type="audio/ogg">
  <source type="audio/mpeg">
</audio>

<script>
var audioTag = document.createElement('audio');
var canPlayAudio = (audioTag.play)? true : false;
if(canPlayAudio) {
    var oggSource = document.getElementById("audiotest").children[0];
    var mp3Source = document.getElementById("audiotest").children[1];
    oggSource.src="test.ogg";
    mp3Source.src="test.mp3";
}
</script>

如果有外部样式表,则在Chrome和Firefox中失败。 Firefox抱怨没有src属性。如果我删除<link rel="stylesheet" src="whatever.css">,那么它将起作用。

我绝对不明白为什么。

有效的测试用例:失败(使用外部样式表):http://www.joshblackburn.com/test1.html作品(无样式表):http://www.joshblackburn.com/test2.html

到底发生了什么?

html5-audio
1个回答
0
投票
这很奇怪。我不确定为什么样式表会引起问题,但是在test1.html中,您可以通过在脚本末尾添加以下行来解决问题:

document.getElementById("audiotest").load()

一种更好的方法可能是将audiotest元素全部从HTML中排除,而仅使用javascript添加即可:

var audio = new Audio(); audio.id = 'audiotest'; audio.src = audio.canPlayType('audio/mpeg') ? 'test.mp3' : 'test.ogg'; audio.volume = 0.2; audio.preload = 'none'; audio.controls = true; document.body.appendChild(audio);

© www.soinside.com 2019 - 2024. All rights reserved.