0

我制作了一个简单的音乐播放器,它有 2 个事件,一个用于更新经过时间,另一个用于持续时间更改……经过时间的功能工作正常,但总时间功能没有……我在http:// www.w3schools.com/tags/ref_av_dom.asp和 durationchange 是一个标准事件,但我不明白为什么它不起作用。我还认为可能是因为脚本是在标签元素之前定义的,但是将脚本移动到文件末尾也不起作用。

这是我的代码:

<!DOCType HTML>
<html>
<head>
<link rel="stylesheet" href="style.css"/>
<script type="text/JavaScript">
    var audio = document.createElement("audio");
    audio.id = "audio1"
    audio.src = "Music.mp3";
    audio.autoplay = true;
    window.onload = function () {
        audio.addEventListener('timeupdate', UpdateTheTime, false);
        audio.addEventListener('durationchange', SetTotal, false);

    }


    function UpdateTheTime() {
           var sec = audio.currentTime;
           var min = Math.floor(sec / 60);
           sec = Math.floor(sec % 60);
           if (sec.toString().length < 2) sec = "0" + sec;
           if (min.toString().length < 2) min = "0" + min;
           document.getElementById('Elapsed').innerHTML = min + ":" + sec;


    }

    function SetTotal() {
        var sec = audio.duration;
        var min = Math.floor(sec / 60);
        sec = Math.floor(sec % 60);
        if (sec.toString().length < 2) sec = "0" + sec;
        if (min.toString().length < 2) min = "0" + min;
        document.getElementById('Total').innerHTML = "/ " + min + " : " + sec;
    }
</script>
</head>
<body>

<form action="/" id="player">
    <img src="Cover.jpg"/>
    <label id="Title">
    Imaginaerum
    </label>
    <label id="Artist">
    Nightwish
    </label>

        <label id="Elapsed">--:--</label>
        <label id="Total">/--:--</label>
</form>

</body>
</html>
4

1 回答 1

1

在您的情况下,在 window.onload 之前触发了 durationchange 事件

        var audio; 
        window.onload = function () {
         audio= document.createElement("audio");
        audio.id = "audio1"
        audio.src = "Music.mp3";
        audio.autoplay = true;
            audio.addEventListener('timeupdate', UpdateTheTime, false);
            audio.addEventListener('durationchange', SetTotal, false);

        }


        function UpdateTheTime() {
               var sec = audio.currentTime;
               var min = Math.floor(sec / 60);
               sec = Math.floor(sec % 60);
               if (sec.toString().length < 2) sec = "0" + sec;
               if (min.toString().length < 2) min = "0" + min;
               document.getElementById('Elapsed').innerHTML = min + ":" + sec;


        }

        function SetTotal() {
            var sec = audio.duration;
            var min = Math.floor(sec / 60);
            sec = Math.floor(sec % 60);
            if (sec.toString().length < 2) sec = "0" + sec;
            if (min.toString().length < 2) min = "0" + min;
            document.getElementById('Total').innerHTML = "/ " + min + " : " + sec;
        }

示例http://jsfiddle.net/rU7SU/

于 2013-08-26T12:58:38.950 回答