[英]adding event listener to audio element doesn't work
i have made a simple music player and there is 2 events for it one for updating elapsed time and another for durationchange...elapsed time's function works fine but total time function doesn't...i have looked up in http://www.w3schools.com/tags/ref_av_dom.asp and durationchange is a standard event but i don't get it why it doesn't work. 我做了一个简单的音乐播放器,它有2个事件,一个用于更新经过的时间,另一个用于持续时间的更改...经过时间的功能正常,但总时间功能不...我在http://中查找www.w3schools.com/tags/ref_av_dom.asp和durationchange是标准活动,但我不明白为什么它不起作用。 i also thought maybe the reason is that script is defined before label elements but moving scripts to the end of file didn't worked either.
我也认为可能是因为脚本是在标签元素之前定义的,但是将脚本移到文件末尾也没有用。
here is my code: 这是我的代码:
<!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>
In your case durationchange event fired before window.onload 在您的情况下,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;
}
Example http://jsfiddle.net/rU7SU/ 示例http://jsfiddle.net/rU7SU/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.