2013-09-01 42 views

回答

1

這裏是一些工作代碼,在這個例子中我保存了一個視頻被觀看到localstorage的次數。

(function($) { 
    $(document).ready(function() { 
     $('video').mediaelementplayer({ 
      success: function (mediaElement, domObject, player) { 
       var duration; 
       var player_counted = false; 
       var i = 0; 

       //lets see that it works! 
       console.log(localStorage[domObject.src+'_times_watched']); 

       //after metadata is loaded we can access the duration 
       mediaElement.addEventListener('loadedmetadata', function(e) { 
        duration = mediaElement.duration; 
       }); 

       //check if video is seen (above 90%) and increase times watched counter 
       mediaElement.addEventListener('timeupdate', function(e) { 
        if((mediaElement.currentTime/duration) >= 0.9) { 
         if(!player_counted) { 
          if (localStorage.getItem(domObject.src+'_times_watched') !== null) { 
           i = parseFloat(localStorage[domObject.src+'_times_watched']); 
          } 
          localStorage[domObject.src+'_times_watched'] = ++i; 
          player_counted = true; 
         } 
        } 
       }, false); 
      } 
     }); 
    }); 
})(jQuery); 

如果您不想使用localstorage,請將其替換 - 並保存到cookie/db或任何您需要的內容。

如果您決定使用localstorage - 您可能還想檢查本地存儲支持,我使用Modernizr if (Modernizr.localstorage) {查看modernizr源代碼或搜索如果您不使用modernizr。

如果您有機會獲得一些獨特的標識:爲每個用戶觀看的影片(即登錄ID /電子郵件),請務必添加domObject.src+'_times_watched'之前,以確保在同一瀏覽器的多個用戶正確計數。

+0

非常感謝@am_;) – miosser

相關問題