简体   繁体   中英

change html5 background video source

I want to change background video source depending on the size of the window. To minimize navigation traffic I don't want to change the video through CSS.

I tried to do this:

<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>

Added <body onload="chsrc()" onresize="chsrc()">

And the html:

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

In chrome console it seems to work but I can't see the video html chrome developer tools

console log chrome developer tools

do you know what I'm wrong about?

Thanks

Fosco

HTML media elements have to be loaded, after you change the source do this...

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

Then you can use the oncanplaythrough event listener to do something after the media has completely loaded and can play through the entire file.

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

That should work for you

Here the solution, it works for me:

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();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM