我正在编写一个 HTML5 控制器并遇到了闭包问题(我认为)。我不确定如何在所有视频标签上使用通用循环,而不是在示例为“简单”执行 getElementByID 时提供的内容。
具体来说,我如何概括所有这些,以便每个视频都具有仅适用于它们的控件。
PS 这是关于学习的,所以解决这个问题的库并不是我真正想要的。
'use strict';
var videos = document.getElementsByTagName('video'), i, vid, controlsBox, play, mute, posterpic;
function playPause(video) {
if (!(video.paused || video.ended || video.seeking || video.readyState < video.HAVE_FUTURE_DATA)) {
video.pause();
play.innerHTML = "Play";
} else {
video.play();
play.innerHTML = "Pause";
}
}
function myAppend(appendTo, toAppend) {
if (appendTo.nextSibling) {
appendTo.parentNode.insertBefore(toAppend, appendTo.nextSibling);
} else {
appendTo.parentNode.appendChild(toAppend);
}
}
for (i = 0; i < videos.length; i += 1) {
vid = videos[i];
vid.controls = false;
vid.addEventListener('click', function () {
playPause(this);
}, false);
// Controls box to display while video is playing
controlsBox = document.createElement('div');
controlsBox.setAttribute("class", 'videoControls');
play = document.createElement('button');
play.type = "Button";
play.setAttribute("class", 'playButton');
play.innerHTML = "Play";
play.addEventListener('click', function () {
playPause(vid);
}(), false);
controlsBox.appendChild(play);
mute = document.createElement('button');
mute.type = "Button";
mute.setAttribute("class", 'muteButton');
mute.innerHTML = "Mute";
mute.addEventListener('click', function () {
vid.volume = 0;
}(), false);
controlsBox.appendChild(mute);
myAppend(vid, controlsBox);
//Finished with controls box
}