html代码
1 <video id="myVideo" class="video-active" width="100%" height="300" controls="controls" > 2 <source src="__STATIC__/video/videos/1.课程介绍.mp4" type="video/mp4" style="margin-top: 0px;;"> 3 <source src="__STATIC__/video/videos/1.课程介绍.mp4" type="video/ogg"> 4 </video>
1、使用jquery写的代码段:
<script> $(document).ready(function() { $times = 10; new_times = 0; $("#video-active").on( "timeupdate", function(event) { onTrackedVideoFrame(this.currentTime, this.duration); } ); }) /** * * @param {Object} currentTime 视频播放的时间 * @param {Object} duration 视频的总播放时间 */ function onTrackedVideoFrame(currentTime, duration) { if(currentTime > $times) { new_times = currentTime; Media = document.getElementById('video-active'); Media.pause(); layer.confirm('你未购买本视频', { btn: ['马上购习', '稍后购买'] //按钮 }, function() { layer.msg('正在开发中,请等待', { icon: 1 }); }, function() { layer.closeAll(); return false; }); } } </script>
2、使用javascript原生态代码(第一种):
<script type="text/javascript"> // 获取 id="myVideo" 的 video 元素 vid = document.getElementById("myVideo"); // // 为 video 元素添加 ontimeupdate 事件,如果当前播放位置改变则执行函数 vid.ontimeupdate = function(){ var curTime = vid.currentTime; console.log(curTime); if (curTime >= 20) { vid.pause(); alert("请购买本视频后再观看!"); return false; } };
3、使用javascript原生态代码(第二种):
vid = document.getElementById("myVideo"); //// videoPlayer.addEventListener("timeupdate", function () { getCurrentVideoPosition(); }, false); vid.addEventListener("timeupdate",function(){ var curTime = vid.currentTime; if (curTime >= 20) { vid.pause(); alert("请购买本视频后再观看"); return false; } })
特别说明:
1、使用javascript共有两种的方法;主要区是有些浏览器不能直接使用timeupdate,只能使用addEvetListener
2、公众号开发视频时,js控制的视频要放在<video><video>下面; 要不然不能执行timeupdate;