2016-11-27 43 views
1

我試圖讓我的自定義視頻控件顯示視頻的當前時間。但是我無法讓它運作。我在代碼中缺少什麼?使用Javascript當前時間功能

JavaScript代碼

var time = document.getElementById("current"); 

time.addEventListener("timeupdate", currentTime, true); 

// Current time function 

function currentTime() { 

    var currentMinutes = Math.floor(video.currentTime/60); 
    var currentSeconds = Math.floor(video.currentTime - currentMinutes * 60); 


    time.innerHTML = currentMinutes + ":" + currentSeconds;  
} 

HTML5

<div id="time"> 
    <span id="current">00:00</span> 
    <span id="duration">00:00</span> 
</div> 
+1

您希望在該「」元素上觸發「timeupdate」事件是什麼? – Pointy

回答

0

你需要有一個事件觸發器關的事件。由於您使用的是視頻,因此我會使用視頻ontimeupdate事件。

顯示時間似乎有問題。但我得到了視頻事件的東西,在這個提琴在這裏工作:https://jsfiddle.net/83peL34r/

的Javascript:

var time = document.getElementById("current"); 
var video = document.getElementById("video"); 

time.addEventListener("timeupdate", currentTime, true); 
video.ontimeupdate = function() {currentTime()}; 

// Current time function 

function currentTime() { 

    var currentMinutes = Math.floor(video.currentTime/60); 
    var currentSeconds = Math.floor(video.currentTime - currentMinutes * 60); 


    time.innerHTML = currentMinutes + ":" + currentSeconds; 

} 

HTML:

<video id="video" width="400" controls> 
    <source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4"> 
</video> 
<div id="time"> 
    <span id="current">00:00</span> 
    <span id="duration">00:00</span> 
</div> 

編輯:我做了一些改動,讓你遠一點。在這一個中,它抓取持續時間並將其放入持續時間部分。如果秒數小於10,則在它前面填上0。

https://jsfiddle.net/83peL34r/1/

+0

謝謝Joshua Terrill。這真的很有幫助。我會確保我記得這一點。 –

0

我假設你有這樣的事情:

<video id="myVideo" width="320" height="176" controls> 
    <source src="mov_bbb.mp4" type="video/mp4"/> 
    <source src="mov_bbb.ogg" type="video/ogg"/> 
</video> 

<div id="time"> 
    <span id="current">00:00</span> 
    <span id="duration">00:00</span> 
</div> 

這樣做:

var video = document.getElementById('myVideo'); 
var currentTime = document.getElementById('current'); 
video.addEventListener('timeupdate', function() { 
    var currentMinutes = Math.floor(video.currentTime/60); 
    var currentSeconds = Math.floor(video.currentTime - currentMinutes * 60); 

    currentTime.innerHTML = currentMinutes + ":" + currentSeconds; 
}); 

在你的代碼,你加入了timeupdate事件監聽到你的跨度。您應該將其添加到視頻元素。