仅在滚动到视图时播放视频

时间:2018-04-09 12:29:22

标签: jquery video html5-video

在此侧滚动页面https://happyprime01.worldsecuresystems.com/video-test.html,第三页和第四页/面板上有一个视频。我希望第三个面板中的视频只在面板进入视图后才开始播放。我有以下使用jquery.appear插件提到here

但我无法让它发挥作用。以下是我的尝试。有人可以帮忙吗?

    <div id="item3" class="item">                   

            <!--video fills page section -->
            <div class="fullscreen-bg">
                <video id="vid-P" muted poster="img/bg-dynamically.jpg" class="fullscreen-bg__video  video-powder">
                    <source src="img/PowderPuff.mp4" type="video/mp4">
                </video>
            </div>                                             

        </div>
    </div>
    <!--end-->

    <script type="text/javascript" src="js/jquery.appear.js"></script>

    <script>

        var myVideo = document.getElementById('vid-P');

    //when div with id item3 is in view play video
   $('#item3').on('appear', function(event, $all_appeared_elements) {


        if (appear) {
              // element is now visible in the viewport
             $("#item3").on('appear', myVideo.play);
            } else {
              // element has gone out of viewport
             $("#item3").on('disappear', myVideo.pause);
            }
  });


    </script>

2 个答案:

答案 0 :(得分:2)

您没有在代码中的任何位置定义appear,因此if (appear) {会失败,因为您的条件为appear = undefined

您可以改为使用appeardisappear事件:

 $('#item3').on('appear', myVideo.play)
            .on('disappear', myVideo.pause);

答案 1 :(得分:0)

本网站上显示的方法对我有用https://cdnjs.com/libraries/vissense/tutorials/autoplay-video与上述类似,但这对我来说很有效。

    var myVideo = document.getElementById('myVideo');

    VisSense.VisMon.Builder(VisSense(myVideo, { fullyvisible: 0.75 }))
    .on('fullyvisible', function(monitor) {
      myVideo.play();
    })
    .on('hidden', function(monitor) {
      myVideo.pause();

    })
    .build()
    .start();