我有这个数组:
var syncData = [
{"end": "1.130","start": "0.849","text": "I'm" },
{"end": "1.390","start": "1.140","text": "seeing" ,"class": "alert"},
{"end": "4.009","start": "3.449","text": "something" }]
我正在“看”中添加该类,因为我想在抄本中更改该单词的样式,与音频同步(参见数组中其他字段的开始和结束时间,以秒为单位)。也就是说,当说“看”时,我希望突出显示背景。
我尝试添加
element.setAttribute("class", "alert");
但是当我这样做时,我在DOM中看到一切都归因于它。这是完整的代码,目前突出了我试过注释的所有单词:
( function(win, doc) {
var audioPlayer = doc.getElementById("audiofile");
var subtitles = doc.getElementById("subtitles");
var syncData = [
{"end": "1.130","start": "0.849","text": "I'm" },
{"end": "1.390","start": "1.140","text": "seeing" ,"class": "alert"},
{"end": "4.009","start": "3.449","text": "something" }
];
createSubtitle();
function createSubtitle()
{
var element;
for (var i = 0; i < syncData.length; i++) {
element = doc.createElement('span');
element.setAttribute("id", "c_" + i);
//element.setAttribute("class", "alert");
element.innerText = syncData[i].text + " ";
subtitles.appendChild(element);
}
audioPlayer.addEventListener("timeupdate", function(e){
syncData.forEach(function(element, index, array){
if( audioPlayer.currentTime >= element.start && audioPlayer.currentTime <= element.end )
subtitles.children[index].style.background = 'yellow';
// var x = subtitles.children[index].getElementsByClassName("alert");
// var j;
// for (j = 0; j < x.length; j++) {
// if( audioPlayer.currentTime >= element.start && audioPlayer.currentTime <= element.end )
// x[j].style.backgroundColor = 'yellow';
// else if (audioPlayer.currentTime > element.start && audioPlayer.currentTime > element.end )
// x[j].style.backgroundColor = 'DarkGrey'; }
//if (audioPlayer.currentTime >= element.start && audioPlayer.currentTime <= element.end )
//subtitles.children[index].getElementsByClassName("alert").style.background = "yellow";
答案 0 :(得分:2)
试试这个:
for (var i = 0; i < syncData.length; i++) {
element = doc.createElement('span');
element.setAttribute("id", "c_" + i);
if(syncData[i].class) element.setAttribute("class", syncData[i].class); // see this line
element.innerText = syncData[i].text + " ";
subtitles.appendChild(element);
}