我做了一個簡單的音樂播放器,有2個事件,它用於更新經過時間,另一個用於durationchange ...經過時間的函數工作正常,但總時間函數doesn' t ...我已經擡頭看了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>
W3Schools的是一個可怕的資源。使用MDN:[教程](https://developer.mozilla.org/en-US/docs/Web/HTML/Using_HTML5_audio_and_video),[文檔](https://developer.mozilla.org/en-US/docs/ Web/API/HTMLMediaElement) –