我制作了一个简单的音乐播放器,有2个事件,一个用于更新已用时间,另一个用于持续时间更改...已用时间的功能正常但总时间功能不...我已查询{ {3}}和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>
答案 0 :(得分: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;
}