html5 video event listener not getting the current time
In relation to my earlier question - Find line of text in relation to a video currentTime and highlight it using javascript? - I have been trying to set the video eventlistener to set the value of the now variable with the video.currentTime. This is the code I currently have (without it returning errors but not actually working).
function transcript(){
var now;
var lines = document.getElementById("transcript").getElementsByTagName("span");
function timeupdate(){
var video = document.getElementsByTagName('video')[0];
video.addEventListener('currentTime', tran, false);
now = video.currentTime;
}
function tran(){
for (var i = 0, l = lines.length; i < l; i++) {
if (now >= +lines[i].getAttribute("data-start") &&
now <= +lines[i].getAttribute("data-end")) {
lines[i].className = "current";
} else {
lines[i].className = "";
}
}}
}
I know that the tran function works, but w开发者_运维技巧hat isn't working is changing the now variable. I also tried to print the current time of the video but that hasn't worked either, so I guess I'm not doing the eventListener properly? Thanks
now is getting calculated when timeupdate is getting called, not when tran is getting called. So if you call tran, now is going to be at the time that timeupdate was called.
To get an accurate now variable, grab the current time in the tran function:
function tran(){
var video = document.getElementsByTagName('video')[0];
now = video.currentTime;
for (var i = 0, l = lines.length; i < l; i++) {
if (now >= +lines[i].getAttribute("data-start") &&
now <= +lines[i].getAttribute("data-end")) {
lines[i].className = "current";
} else {
lines[i].className = "";
}
}}
精彩评论