播放随机音乐

时间:2013-01-18 07:33:31

标签: javascript html

我想在我的网站上播放随机音轨..没有任何前进/后退控制.. 我正在使用的代码是..

<script type="text/javascript">
var a = Math.random()*2;
a=Math.floor(a);

if(a==1)
{alert(a); document.getElementById('soundtrack').innerHTML="<audio id='background_audio1' loop autoplay><source src='6.ogg' type='audio/ogg'>Your browser does not support the audio element.</audio>";}
if(a==0)
{alert("hello");document.getElementById('soundtrack').innerHTML="<audio id='background_audio1' loop autoplay><source src='5.ogg' type='audio/ogg'>Your browser does not support the audio element.</audio>";}

</script>

<div id="soundtrack">

</div>

但是这段代码没有播放任何东西..(警报很顺利) 我该怎么做???

2 个答案:

答案 0 :(得分:0)

实际上,在运行脚本时不会初始化div。你需要将它放在onload hadler中。这个例子对我有用:

<script type="text/javascript">
function play()
{
    var a = Math.random()*2;
    a=Math.floor(a);

    if(a==1)
    {
        alert(a); 
        document.getElementById('soundtrack').innerHTML="<audio id='background_audio1' loop autoplay><source src='1.mp3' type='audio/ogg'>Your browser does not support the audio element.</audio>";
    }
    if(a==0)
    {
        alert(document.getElementById('soundtrack'))
        document.getElementById('soundtrack').innerHTML="<audio id='background_audio1' loop autoplay><source src='0.mp3' type='audio/ogg'>Your browser does not support the audio element.</audio>";
    }
}
</script>
<body onload="play()">;
<div id="soundtrack">

</div>
</body>

答案 1 :(得分:0)

这是(一个原因)为什么将JavaScript放在BODY标记的末尾是个好主意。正如Mikhail所说,脚本运行时尚未加载DIV标记。 HTML页面按您键入的顺序处理(除非您使用函数和事件处理程序)。一个简单的解决方法就是将DIV移动到页面顶部,如下所示:

<html>
<body>
<div id="soundtrack"></div>

<script type="text/javascript">
var a = Math.random()*2;
a=Math.floor(a);

if(a==1)
{alert(a); document.getElementById('soundtrack').innerHTML="<audio id='background_audio1' loop autoplay><source src='6.ogg' type='audio/ogg'>Your browser does not support the audio element.</audio>";}
if(a==0)
{alert("hello");document.getElementById('soundtrack').innerHTML="<audio id='background_audio1' loop autoplay><source src='5.ogg' type='audio/ogg'>Your browser does not support the audio element.</audio>";}

</script>
</body>
</html>