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

<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>


但是这段代码没有发挥任何作用..(警报进展顺利)
我该怎么办???

最佳答案

实际上,在运行脚本时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>

关于javascript - 播放随机音乐,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14394336/

10-09 18:22