推广为视频添加控件

时间:2012-10-21 11:48:18

标签: javascript

我正在编写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
}

1 个答案:

答案 0 :(得分:0)

您可以在每个视频元素上添加控件的引用 在循环中调用myAppend之前添加以下语句。

vid.controlsBox = controlsBox;
vid.muteControl = mute;
vid.playControl = play;

然后playPause函数应该是这样的:

function playPause(video) {
    if (!(video.paused || video.ended || video.seeking || video.readyState < video.HAVE_FUTURE_DATA)) {
        video.pause();
        video.playControl.innerHTML = "Play";
    } else {
        video.play();
        video.playControl.innerHTML = "Pause";
    }
}

对于需要访问相关控件的其他视频功能,请使用上面的controlBoxmuteControlplayControl

如果您需要访问关联的对象,还可以将视频元素和控件的引用放入controlsBox元素中。只需在循环中添加以下语句即可。

controlsBox.video = vid;
controlsBox.muteControl = mute;
controlsBox.playControl = play;