单击暂停HTML5视频播放器

时间:2015-09-14 08:15:08

标签: javascript jquery html5 video

我想在点击视频后暂停我的视频。

在控制台中使用命令时,一切正常。但是,如果我使用jQuery它不起作用。谁知道为什么?

       $("#video").click(function() {
            if(!$("#video").get(0).paused) {
                console.log("playing");
                showPlayBtn();
                $("#video").get(0).pause();
            } else {
                console.log("paused");
            }
        });

HTML:

<video id="video" preload="auto">
    <source src="path/to/video.mp4" type="video/mp4">
    Your browser does not support the Videoplayer
</video>

2 个答案:

答案 0 :(得分:1)

由于.pause()是本机VideoElement的方法而不是jQuery的方法,因此您需要对它进行引用。但是使用:$("#video").get(0)来引用处理函数内部的视频对象并不是必须的,而只能使用引用同一对象的 this

您可以查看:

$("#video").click(function() {
    console.log($("#video").get(0)==this);  //true 
}

我已经在2个不同的浏览器中检查了您的代码,但确实有效。但也许您尝试在实际加载之前调用 $(&#34;#video&#34;)。 解决这个问题 - 加载后添加它,例如:

$(function(){
    //inside here -> means after loading. So video element already exist
    $("#video").click(function() {
        if(!this.paused) {  //if this video element is NOT paused
            console.log("playing");
            showPlayBtn();  //some function of yours
            this.pause();  //pause this video element
        } else {
            console.log("paused");
        }
    });
});

答案 1 :(得分:0)

您的代码错误地错过了if支票内的选择器:

    $("#video").click(function() {
        if(!$(this).get(0).paused) {
            console.log("playing");
            showPlayBtn();
            $(this).get(0).pause();
        } else {
            console.log("paused");
        }
    });

或者更有效率:

    $("#video").click(function() {
        var video = $(this).get(0);
        if(!video.paused) {
            console.log("playing");
            showPlayBtn();
            video.pause();
        } else {
            console.log("paused");
        }
    });

这是我的html5的jQuery播放/暂停包装器 - 当它不被支持时,事物被包装在try / catch中:

/**
 * Play an audio or video element
 * @method play
 * @for jQuery
 * @chainable
 * @return {jQuerySelector}
 */
$fn.play = function() {
    return this.each(function() {
        try {
            this.play();
        } catch (e) {
        }
    });
};

/**
 * Pause an audio or video element
 * @method pause
 * @for jQuery
 * @chainable
 * @return {jQuerySelector}
 */
$fn.pause = function() {
    return this.each(function() {
        try {
            this.pause();
        } catch (e) {
        }
    });
};
相关问题