我正在通过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
到底发生了什么?
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);