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;