javascript 无法停止后台播放隐藏 DIV 中的 YouTube 视频

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13682049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:27:33  来源:igfitidea点击:

Can't Stop YouTube Video in Hidden DIV Playing in the background

javascriptjqueryyoutube

提问by 0rchard

I've tried various things but can't get a YouTube video in a hidden DIV to stop playing in the background before the DIV toggle is even clicked. visibility:hidden didn't seem to solve the issue. Here's the code I'm using. Hope someone can help! I can turn off autoplay to solve it, but then it means users have to click an extra button (the YouTube 'play' button) which isn't ideal.

我尝试了各种方法,但无法在隐藏的 DIV 中获取 YouTube 视频以在单击 DIV 切换按钮之前停止在后台播放。可见性:隐藏似乎没有解决问题。这是我正在使用的代码。希望有人能帮忙!我可以关闭自动播放来解决它,但这意味着用户必须点击一个额外的按钮(YouTube 的“播放”按钮),这并不理想。

** IN THE OF THE WEB PAGE:

** 在网页上:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">

$(document).ready(function(){

        $(".productDescription").hide();
        $(".show_hide").show();

    $('.show_hide').click(function(){
    $(".productDescription").slideToggle();
    return false;
    });

});

</script>

** IN THE BODY:

** 在身体里:

<div class="productDescription">

<iframe width="715" height="440" src="http://www.youtube.com/embed/BLbTegvRg0U?&amp;wmode=transparent&amp;autoplay=0" frameborder="0" allowfullscreen></iframe> 
<div class="closebutton"><a href="index.php" onClick="javascript:location.replace(this.href);" class="show_hide">Close Video</a>
</div>
</div>

** AND IN THE STYLESHEET:

** 在样式表中:

.productDescription {
display: block;
position:absolute;
left:0px;
top:-2px;
z-index:5;
background-color: #000;
margin: 0px;
float: left;
padding: 0px;
width: 715px;
min-height: 600px;
height: 600px;
}

.show_hide {
display:none;
}

.closebutton {
display: block;
width:120px;
height: 22px;
position:absolute;
left:20px;
top:50px;
background-color: #000;
padding-top: 3px;
float: left;
z-index: 9999;
}

Thanks very much in advance!

首先十分感谢!

回答by Bryan Gentry

The autoplay feature will start to play the video once it is loaded, whether the div is visible or hidden.

自动播放功能将在视频加载后开始播放,无论 div 是可见的还是隐藏的。

However, if you remove the autoplay setting, you can then use a YouTube API to control the video so that the video will start playing when a person clicks to show the div. One option is the iframe API(which I would recommend since you are already using iframe to embed the video, and this allows YouTube to serve up an HTML5 video rather than a flash video if the viewer is on a mobile device) and another option is the JavaScript API.

但是,如果您删除自动播放设置,则可以使用 YouTube API 来控制视频,以便在有人单击以显示 div 时开始播放视频。一种选择是iframe API(我推荐它,因为您已经在使用 iframe 嵌入视频,如果观看者在移动设备上,这允许 YouTube 提供 HTML5 视频而不是 Flash 视频),另一种选择是的的JavaScript API

Because you asked for more details, here is a quick explanation of how to use the YouTube iFrame API to meet your needs. I recommend reading the documentation so you can understand what is going on and adapt it as needed.

由于您询问了更多详细信息,这里简要说明如何使用 YouTube iFrame API 来满足您的需求。我建议您阅读文档,以便您了解正在发生的事情并根据需要进行调整。

First, in your HTML create your iframe video the same way you did above, but add two things: an ID for the iframe and an origin parameter in the iframe src. (The origin parameter helps keep you YouTube player safe from javascript hacking.) So it would look like this:

首先,在您的 HTML 中以与上述相同的方式创建 iframe 视频,但添加两件事:iframe 的 ID 和 iframe src 中的 origin 参数。( origin 参数有助于保护您的 YouTube 播放器免受 javascript 黑客攻击。)所以它看起来像这样:

<iframe id="player" width="715" height="440" src="http://www.youtube.com/embed/BLbTegvRg0U?&amp;wmode=transparent&amp;autoplay=0&origin=http://example.com/" frameborder="0" allowfullscreen></iframe>

Replace the example.com url with the website this page will be on.

将 example.com url 替换为该页面所在的网站。

Somewhere after the iframe, but before the </body>tag, add this code to load the api and initialize the player:

在 iframe 之后的某个地方,但在</body>标记之前,添加此代码以加载 api 并初始化播放器:

  <script>
  var tag = document.createElement('script');
  tag.src = "//www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player');
  }
</script>

Then, in your javascript, just before the line that reads $('.productDescription').slideToggle(), add this code:

然后,在您的 javascript 中,就在读取 $('.productDescription').slideToggle() 的行之前,添加以下代码:

  if ($('.productDescription').is(':visible')) {
       player.pauseVideo();
      }
  else {
       player.playVideo();
      }

This code will test to see whether the .productDescriptiondiv is visible. If it is hidden, it will start the video and display the div. If it is not visible, it will pause the video and hide the div.

此代码将测试以查看.productDescriptiondiv 是否可见。如果它是隐藏的,它将启动视频并显示 div。如果它不可见,它将暂停视频并隐藏 div。

That should do it.

那应该这样做。

回答by ahkeno

I have same issue, but I could fix with this.Refer to YouTubeAPI,we can't implement directly.So I edit this way.

我有同样的问题,但我可以解决这个问题。参考YouTubeAPI,我们不能直接实现。所以我这样编辑。

Step1: Creat loadYTScript()function and put youtubeAPI code,

Step1:创建loadYTScript()函数并放入youtubeAPI代码,

Step2: is call function onYouTubeIframeAPIReady() Then at onclick call the load function. Here is your js code:

Step2:调用函数onYouTubeIframeAPIReady() 然后在onclick 调用加载函数。这是你的js代码:

function loadYTScript(){
                    var tag = document.createElement('script');
                    tag.src = "https://www.youtube.com/iframe_api";
                    var firstScriptTag = document.getElementsByTagName('script')[0];

                    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);    
                }
        function onYouTubeIframeAPIReady() {
                    player = new YT.Player('player', {                                         
            height: '390',
            width: '640',
            videoId: 'M7lc1UVf-VE',
                        events: {
                            'onReady': onPlayerReady,
                          }
                    });
                }
                function onPlayerReady(event) {
                    event.target.playVideo();
                }
                jQuery(document).ready(function()    {
                $('.show_hide').click(function(){
    $(".productDescription").slideToggle();
    loadYTScript();
    });
    });

At html don't forget to add

在 html 不要忘记添加

<div class="productDescription">        
            <div id="player"></div>
        </div>

Hope it work well.

希望它运作良好。