简体   繁体   English

更改 html5 背景视频源

[英]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.为了尽量减少导航流量,我不想通过 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()">添加<body onload="chsrc()" onresize="chsrc()">

And the html:和 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在 chrome 控制台中它似乎可以工作,但我看不到视频html chrome 开发人员工具

console log chrome developer tools控制台日志 Chrome 开发人员工具

do you know what I'm wrong about?你知道我错在哪里吗?

Thanks谢谢

Fosco福斯科

HTML media elements have to be loaded, after you change the source do this...必须加载 HTML 媒体元素,在更改源后执行此操作...

//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.然后,您可以使用oncanplaythrough事件侦听器在媒体完全加载并可以播放整个文件后执行某些操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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