更改html5背景视频源

时间:2017-08-29 15:35:30

标签: javascript html5 html5-video

我想根据窗口的大小更改背景视频源。 为了最大限度地减少导航流量,我不想通过CSS更改视频。

我试着这样做:

<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

2 个答案:

答案 0 :(得分: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
);

这应该对你有用

答案 1 :(得分:0)

这里有解决方案,对我有用:

var video = document.getElementById('video_home');
var source = document.getElementById('video_source');

function chsrc(event) {
   var winSize = window.innerWidth || document.body.clientWidth;
   if (winSize <= 768) {
      source.setAttribute('src', 'video_mobile.mp4');
      video.load();
   } else {
      source.setAttribute('src', 'video.mp4');
      video.load();
   }
}