2017-08-29 145 views
0

我想根據窗口的大小更改背景視頻源。 爲了儘量減少導航流量,我不想通過CSS更改視頻。更改html5背景視頻源

我試着這樣做:

<script> 
function chsrc() { 
    var larghezza_browser = window.innerWidth || document.body.clientWidth; 
    if (larghezza_browser > 1540) { 
     console.log('carico il video grande - larghezza: ' + larghezza_browser + 'px'); 
     document.getElementById("mp4_desktop").src="//sullimite.it/wp-content/themes/sullimite/fosco/modella_schermo_grande.mp4"; 
     document.getElementById("webm_desktop").src="//sullimite.it/wp-content/themes/sullimite/fosco/modella_schermo_grande.webm"; 
    } else { 
     console.log('carico il video piccolo - larghezza: ' + larghezza_browser + 'px'); 
     document.getElementById("mp4_desktop").src="//sullimite.it/wp-content/themes/sullimite/fosco/modella_schermo_piccolo.mp4"; 
     document.getElementById("webm_desktop").src="//sullimite.it/wp-content/themes/sullimite/fosco/modella_schermo_piccolo.webm"; 
    } 
} 
</script> 

新增<body onload="chsrc()" onresize="chsrc()">

和HTML:

<video autoplay loop muted id="video_home"> 
<source id="mp4_desktop" type="video/mp4" /> 
<source id="webm_desktop" type="video/webm" /> 
</video> 

在Chrome控制檯它似乎工作,但我不能看視頻 html chrome developer tools

console log chrome developer tools

你知道我錯了嗎?

感謝

Fosco

回答

1

HTML媒體元素已經被加載,更改源做到這一點之後......

//this line loads the media for the given id 
document.getElementById("webm_desktop").load(); 

然後你可以使用oncanplaythrough事件監聽器做一些事情媒體完成加載後可以播放整個文件。

document.getElementById("webm_desktop").oncanplaythrough(
//play the video here 
//do something here too if you want 
); 

這應該爲你工作

+0

對不起,我不知道該怎麼做你的建議對我有多重要。 –

+0

@FoscoVentura看到我的編輯。我更詳細地解釋這兩條線。 – SidTheBeard

+0

我不能做你說的,但我解決了從webm_desktop到video_home更改getElementById的問題。我也刪除了MP4並只使用了webm –