在JavaScript中隐藏/显示 - 停止播放YouTube iframe视频 [英] Hide/show in JavaScript - stop playing YouTube iframe video

查看:1643
本文介绍了在JavaScript中隐藏/显示 - 停止播放YouTube iframe视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了iframe功能来嵌入视频,我通过JavaScript隐藏/显示内容和视频。

I've used the iframe function to embed videos, and I'm hiding/showing the content and videos through JavaScript.

我有 一个 问题。当我在第一个视频上按下播放,然后在不停止第一个视频的情况下点击下一个视频时,第一个视频继续播放。

I have one problem. When I press play on the first video, and then click on the next without stopping the first one, the first one just keeps on playing.

我该怎么做才能停止显示新内容时背景中的视频?

What can I do to stop the video in the "background", when showing new content?

$(function(){
    $("#link1").click(show1);
});

function show1(){
    $("#pic1").fadeIn();
    $("#pic2").hide();
}

我只是使用这个简单的JavaScript函数,其中pic1和pic2id是div的id,视频是嵌入的。

I'm just using this simple JavaScript function, where the "pic1" and "pic2" id is the id of the div, the video are embedded in.

我似乎无法使其正常工作。我试图删除,但如果你愿意,你就不能再看到视频了。

I just can't seem to make it work. I tried to put remove, but then you can't see the video again if you want to.

推荐答案

这是一个实现YouTube播放器API,无需加载其他文件。要完成这项工作,您必须使用<$ c后缀所有< iframe> src 属性$ c>?enablejsapi = 1 。

This is an implementation of the YouTube player API, without loading additional files. To get this work, you have to suffix all of your <iframe>'s src attribute with ?enablejsapi=1.

示例(为了便于阅读,我将代码分解了几行,您可以安全地省略换行符) :

Example (I broke the code over a few lines for readability, you can safely omit the linebreaks):

<div id="pic3">
    <iframe width="640" height="390"
            src="http://www.youtube.com/embed/Xub4grFLbQM?enablejsapi=1"
            frameborder="0" allowfullscreen></iframe>
</div>

<div id="tS2" class="jThumbnailScroller">
.. Removed your code for readability....
    <a href="#vid3" id="link3"><img src="images/thumbs/player2.jpg" height="85"/></a>
    ....

JavaScript + jQuery代码:

JavaScript + jQuery code:

$(function() {
    /* elt: Optionally, a HTMLIFrameElement. This frame's video will be played,
     *       if possible. Other videos will be paused*/
    function playVideoAndPauseOthers(frame) {
        $('iframe[src*="http://www.youtube.com/embed/"]').each(function(i) {
            var func = this === frame ? 'playVideo' : 'pauseVideo';
            this.contentWindow.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
        });
    }
    $('#tS2 a[href^="#vid"]').click(function() {
        var frameId = /#vid(\d+)/.exec($(this).attr('href'));
        if (frameId !== null) {
            frameId = frameId[1]; // Get frameId
            playVideoAndPauseOthers($('#pic' + frameId + ' iframe')[0]);
        }
    });
});

这篇关于在JavaScript中隐藏/显示 - 停止播放YouTube iframe视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆