2017-02-24 104 views
3

我試過了在這裏找到的幾個答案。使用JavaScript獲取HTML5視頻的寬度和高度?

此代碼適用於Firefox並輸出正確的大小,但不適用於Chrome或IE。

主要是我試圖得到寬度。

我有輸出用3個例子的視頻下方的寬度。

https://jsfiddle.net/a8a1o8k2/

的JavaScript

https://stackoverflow.com/a/4129189/6806643

var vid1 = document.getElementById("video"); 
vid1.videoHeight; // returns the intrinsic height of the video 
vid1.videoWidth; // returns the intrinsic width of the video 

返回0

https://stackoverflow.com/a/9333276/6806643

var vid2 = document.getElementById("video"); 
vid2.addEventListener("loadedmetadata", function (e) { 
    var width = this.videoWidth, 
     height = this.videoHeight; 
}, false); 

返回0

https://stackoverflow.com/a/16461041/6806643

var vid3 = document.getElementById("video"); 
var videotag_width = vid3.offsetWidth; 
var videotag_height = vid3.offsetHeight; 

有時返回正確的值
有時會返回300(默認播放器的大小,如果沒有視頻源)

回答

1

編輯:改進的方案後,我確實閱讀了跨瀏覽器的問題。

以下解決方案適用於Chrome和Firefox。問題在於Firefox不像Chrome那樣對待readyState。

var vid2 = document.getElementById("video"); 
vid2.addEventListener("loadedmetadata", getmetadata); 

if (vid2.readyState >= 2) { 
    getmetadata(vid2); 
} 

function getmetadata(){ 
    document.getElementById('output2').innerHTML = "Test 2: " + vid2.videoWidth; 
} 

更新JSFiddle

+0

你可以顯示它在jsfiddle中返回值嗎?我沒有正確使用文檔寫入輸出。 –

+0

是的,它確實顯示**測試2:640 ** – nbo

+0

它在Chrome中顯示測試2:640,但在Firefox中顯示爲空白。 –

0

如果你想定義的大小你視頻與Java腳本im不知道你實際上正在做什麼,雖然在我看來,你只是希望它可以像這個例子一樣定製。

如果我們假定視頻嵌入下面的代碼可能做的伎倆

// Find all YouTube videos 
var $allVideos = $("iframe[src^='//www.youtube.com']"), 

    // The element that is fluid width 
    $fluidEl = $("body"); 

// Figure out and save aspect ratio for each video 
$allVideos.each(function() { 

    $(this) 
    .data('aspectRatio', this.height/this.width) 

    // and remove the hard coded width/height 
    .removeAttr('height') 
    .removeAttr('width'); 

}); 

// When the window is resized 
$(window).resize(function() { 

    var newWidth = $fluidEl.width(); 

    // Resize all videos according to their own aspect ratio 
    $allVideos.each(function() { 

    var $el = $(this); 
    $el 
     .width(newWidth) 
     .height(newWidth * $el.data('aspectRatio')); 

    }); 

// Kick off one resize to fix all videos on page load 
}).resize(); 

您也可以參考這個網頁它實際上是如何工作的,並也有動態視頻重新調整爲CSS和HTML例子好:

https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php

+0

我會看看這個。我只是使用了一個