2014-06-19 226 views
0

我想從瀏覽器中的本地磁盤播放視頻文件,所以我找到了這個代碼。你能告訴我爲什麼它不起作用嗎?在jsfiddle它的作品,但是當我把它複製到項目中將無法正常工作。你也可以告訴我什麼給函數聲明像function name(x){variables}(window)HTML視頻播放器

我得到的錯誤是Uncaught TypeError: Cannot read property 'addEventListener' of null

感謝您的幫助:)

<html> 
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
</head> 
<body> 

    <script> 
     (function localFileVideoPlayerInit(win) { 
      var URL = win.URL || win.webkitURL, 
        playSelectedFile = function playSelectedFileInit(event) { 
         var file = this.files[0]; 
         var type = file.type; 
         var videoNode = document.querySelector('video'); 
         var canPlay = videoNode.canPlayType(type); 
         canPlay = (canPlay === '' ? 'no' : canPlay); 
         var message = 'Can play type "' + type + '": ' + canPlay; 
         var isError = canPlay === 'no'; 
         displayMessage(message, isError); 
         if (isError) { 
          return; 
         } 
         var fileURL = URL.createObjectURL(file); 
         videoNode.src = fileURL; 
        }, 
        inputNode = document.querySelector('input'); 
      if (!URL) { 
       displayMessage('Your browser is not ' + 
         '<a href="http://caniuse.com/bloburls">supported</a>!', true); 
       return; 
      } 
      inputNode.addEventListener('change', playSelectedFile, false); 
     }(window)); 
    </script> 

    <h1>HTML5 local video file player example</h1> 
    <div id="message"></div> 
    <input type="file" accept="video/*"/> 
    <video controls autoplay></video> 
</body> 
</html> 

回答

1

的問題是,你的代碼運行之前DOM就緒/加載。

有兩種方法可以解決這個問題。

1)將以下<video controls autoplay></video>

2)使用document.addEventListener("DOMContentLoaded", function() { });這樣的整個JavaScript代碼塊:

<script> 
document.addEventListener("DOMContentLoaded", function() { 
    var URL = window.URL || window.webkitURL, 
      playSelectedFile = function playSelectedFileInit(event) { 
       var file = this.files[0]; 
       var type = file.type; 
       var videoNode = document.querySelector('video'); 
       var canPlay = videoNode.canPlayType(type); 
       canPlay = (canPlay === '' ? 'no' : canPlay); 
       var message = 'Can play type "' + type + '": ' + canPlay; 
       var isError = canPlay === 'no'; 
       displayMessage(message, isError); 
       if (isError) { 
        return; 
       } 
       var fileURL = URL.createObjectURL(file); 
       videoNode.src = fileURL; 
      }, 
      inputNode = document.querySelector(("input[type=file]")); 
    if (!URL) { 
     displayMessage('Your browser is not ' + 
       '<a href="http://caniuse.com/bloburls">supported</a>!', true); 
     return; 
    } 
    inputNode.addEventListener('change', playSelectedFile, false); 
}); 
</script> 
+0

謝謝!所以函數聲明意味着函數名(x){}(窗口)中的{}後面的參數()中的參數將是x的默認參數? :) – KorWojci

+0

Parens在函數表達式的末尾調用函數。 Parens只是調用語法。傳遞給函數的參數依然存在。 –

+0

謝謝Latheesan :) – Cesare