2017-08-29 123 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 –