通过JavaScript添加HTML5音频源仅在存在外部样式表时才有效



我正在通过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

这到底是怎么回事?

这很奇怪。我不知道样式表为什么会引起问题,但在test1.html中,您可以通过在脚本末尾添加以下行来解决问题:

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

一个更好的方法可能是从HTML中排除audiotest元素,然后简单地使用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);

最新更新