页面中存在多个视频,当视频完全显示在屏幕中时自动播放,在屏幕外自动停止播放,功能类似微博的视频播放。
代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .div_banner { height: 100px; 80%; margin: auto; background-color: #ffffcc } .div_video { height: 300px; 600px; margin: auto; background-color: black; color: aliceblue; line-height: 300px; font-size: 26px; text-align: center; } video { height: 300px; auto; } </style> </head> <body style="margin:auto"> <div class="div_banner" style="height:2000px"></div> <div class="div_video" id="video1"> <video src="img/video/嘉n华.1080p.HD国语中字[最新电影www.6vhao.tv].mp4" controls="controls"></video> </div> <div class="div_banner"></div> <div class="div_video" id="video2"> <video src="img/video/嘉n华.1080p.HD国语中字[最新电影www.6vhao.tv].mp4" controls="controls"></video> </div> <div class="div_banner" style="height:2000px"></div> </body> <script src="lib/jquery-3.1.1.min.js"></script> <script> //页面滚动,其中完全显示的视频自动播放 $(document).scroll(function () { var isVideoOn = false; $('.div_video video').each(function () { var $video = $(this); var toTop = $video.offset().top - $(document).scrollTop(); var toBottom = window.innerHeight - (toTop + $video.height()); if (toTop > 0 && toBottom > 0) {//完全显示在屏幕中 if (!isVideoOn) { $video[0].play(); isVideoOn = true; } else { $video[0].pause(); } } else {//在屏幕外 $video[0].pause(); } }) }) </script> </html>
效果如下: