滚动到时自动播放Youtube视频 [英] Autoplay Youtube Video When Scrolled to

查看:96
本文介绍了滚动到时自动播放Youtube视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在页面上滚动到YouTube视频时,是否可以自动播放该视频?我试图用谷歌搜索它,看起来有一些旧的youtube嵌入代码的方法.我正在寻找更新的版本-有人知道您在页面上向下滚动一定数量的像素时如何自动播放youtube视频吗?

Is there any way to autoplay a youtube video when you scroll to it on the page? I've tried to google this and it looks like theres some methods for the old youtube embed code. I'm looking for an updated version of this - does anyone know how to automatically play youtube videos when you scroll down a certain amount of pixels on a page?

感谢您的帮助

推荐答案

<iframe id="ytplayer" type="text/html" width="640" height="390"
  src="http://www.youtube.com/embed/M7lc1UVf-VE?autoplay=1&origin=http://example.com"
  frameborder="0"/>

使用以上方法自动播放视频.根据您的问题只在向下滚动时才播放,请选中此线程.

Use the above to play the video automatically. per your question to play it only when scrolled down, check this thread.

根据滚动位置触发视频自动播放

这是完整的代码.已经在Firefox和Chrome上进行了测试.您可以在此处查看示例.

Here is the complete code. have tested this on firefox and chrome. You can check the sample working here.

http://www.foftv.com/samplejs/vidscroll2.html

<html><head>
    <style>
    #e1, #e2, #e3, #e4, #e5, #  ytplayer{ 
        height:390px; width:640px; display: block;
        opacity: 0;
    }
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
      // Load the IFrame Player API code asynchronously.
      var tag = document.createElement('script');
      tag.src = "https://www.youtube.com/player_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

      // Replace the 'ytplayer' element with an <iframe> and
      // YouTube player after the API code downloads.
      var player;
      function onYouTubePlayerAPIReady() {
        player = new YT.Player('ytplayer', {
          height: '390',
          width: '640',
          playerVars : {
                autoplay : 0
            },
          videoId: 'M7lc1UVf-VE'
        });
      }

      $(window).scroll(function() {
        $("iframe").each( function() {
            if( $(window).scrollTop() > $(this).offset().top - 200 ) {
                $(this).css('opacity',1);
                player.playVideo();
            } else {
                $(this).css('opacity',0);
                player.stopVideo();
            }
        }); 
    });

    </script>
    </head>
    <body>



    <div id="e1">Some element 1</div>
    <div id="e2">Some element 2</div>
    <div id="e3">Some element 3</div>
    <div id="ytplayer">Youtube player here</div>
    <div id="e4">Some element 4</div>
    <div id="e5">Some element 5</div>
    </body>
    </html>

这篇关于滚动到时自动播放Youtube视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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