如果部分有课程而不是开始播放视频

时间:2015-06-13 11:22:13

标签: javascript jquery html5-video

在滚动#video-section时,请帮助我自动制作视频播放.visible班级名称。反之亦然,当.visible类名称将从节中删除时,视频将被停止。 感谢。

<section class="cd-section">
        some content
</section>
<section id="video-section" class="cd-section">
    <video>
        <source src="http://www.w3schools.com/tags/movie.mp4" type="video/mp4">
    </video>
</section>
<section class="cd-section">
        some content
</section>

JSFiddle在这里https://jsfiddle.net/y896ec5x/

3 个答案:

答案 0 :(得分:0)

你需要检查视频部分中是否可见类,如果它是播放视频,否则停止它,你需要在滚动事件上检查这个,我添加了可滚动的主体,但如果它在其他标签内用它。

$("body").scroll(function() {
    if ($('#video-section').hasClass('visible')) {
       $("video").play();
    } else {
        $("video").pause();
    }
});

答案 1 :(得分:0)

使用算法从Check if element is visible after scrolling查看元素是否完全,您可以

$(window).scroll(function() {
  if (isScrolledIntoView('#video')) {
    $('#video').get(0).play();
  } else {
    $('#video').get(0).pause();
  }
});

function isScrolledIntoView(elem) {
  var $elem = $(elem);
  var $window = $(window);

  var docViewTop = $window.scrollTop();
  var docViewBottom = docViewTop + $window.height();

  var elemTop = $elem.offset().top;
  var elemBottom = elemTop + $elem.height();

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
.cd-section {
  height: 100vh;
}

#video {
  height: 50vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<section class="cd-section">
  some content
</section>
<section id="video-section" class="cd-section">
  <video id="video">


    <source src="http://www.w3schools.com/tags/movie.mp4" type="video/mp4">
      <source src="http://www.w3schools.com/tags/movie.ogg" type="video/ogg">
        Your browser does not support the video tag.
  </video>
</section>
<section class="cd-section">
  some content
</section>

答案 2 :(得分:0)

您正在做什么(根据评论):

$("video").play();
// or
$("video").pause();

无效,因为jQuery本身没有这些功能。

尝试使用$.get方法,该方法返回元素的常规JavaScript DOM对象:

$("video").get(0).play();
// or
$("video").get(0).pause();

然后在滚动(没有滚动条的视差站点)检测到这一点,将其包裹在轮子事件中以处理:

$("html, body").bind("mousewheel", function(){
  if ($("#video-section").hasClass("visible")) {
    $("video").get(0).play()
  } else {
    $("video").get(0).pause();
  }
});