开发者

Find line of text in relation to a video currentTime and highlight it using javascript?

What I aim to do is have some text and using JavaScript change the colour of the text when the currentTime of the embedded video is between the start and end tags. I have some text as below, what is the best way, using JavaScript, to cycle through it and read the start and end tags?

<div id="transcript">
<h3>Transcript</h3>
<p class="tran">
<span tag="ID_1" start="0" end="6">transcript line #1</span>
<span tag="ID_2" start="6" end="9"> transcript line #2</span>
</p>
</div>

Using tutorials I have managed to hide text and show it as captions, but what I really want to do is show the full text and just highlight the current part. Using something like this below.

 for (var i = 0; i < transcriptlength; i++) {
 if (now >= tran.start && now <= tran.end){
 span.style.color = red; // 
 break;
 }}

I'm not sure if document.getElementById(transcript) would work in getting all 开发者_StackOverflow社区the data. Any help would be much appreciated. Thanks!


You could do what you're after like this:

var lines = document.getElementById("transcript").getElementsByTagName("span"); 
var now = 4;

for (var i = 0, l = lines.length; i < l; i++) {
  if (now >= +lines[i].getAttribute("start") && 
      now <= +lines[i].getAttribute("end")) {
    lines[i].style.color = "red";
    break;
  }
}

You can test it here///but since we're using invalid attributes, might as well use HTML5 valid data- attributes (e.g. data-start instead of start), and I'd also use a class for styling, like this:

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 = "";
  }
}

You can test that version here, it allows you to more easily style that span by simply changing the .current class in the CSS. Also, as the video progresses, this will clear the styling from the previously selected element, getting the "current line" effect you're after.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜