html - 中心全屏背景视频

标签 html css video background css-position

我最近在玩 html5 并想到了使用的想法

使用以下 html 代码作为网站背景的全屏视频:

<video id = "video_background" preload = "auto" autoplay = "true" loop = "loop">
  <source src = "videos/football.mp4" type = "video/mp4" />
</video> 

此外,我使用了以下 css 代码来正确对齐它:

#video_background{
    position: absolute;
    bottom: 0px;
    right: 0px;
    min-width: 100%;
    min-height: 100%;
    max-width: 4000%;
    max-height:4000%;
    width: auto;
    height: auto;
    z-index: -1000;
    overflow: hidden;
}  

效果很好,但我想让我的视频水平居中 在每个浏览器分辨率上。

无论我尝试以何种方式实现此效果(通过 margin 或基于百分比的定位), 视频一直停留在右下角。

关于如何解决这个“问题”有什么想法吗?

最佳答案

这是我很久以前写的一个 JQuery 函数,用于使视频成为全屏背景。本质上,如果窗口的纵横比高于视频的纵横比,则将高度设置为 100%,将宽度设置为自动,反之亦然,以获得更宽的纵横比窗口。

// Resize the video elements so that we don't get any borders due to aspect ratio
function resizeVideo() {
  if ($(window).height() > $(window).width() * 0.5425) { // Which dimension is bigger dependant on aspect ratio (16:9)
    $("video").removeAttr("height").removeAttr("width").width("auto").height("100%");
  }
  else {
    $("video").removeAttr("height").removeAttr("width").width("100%").height("auto");
  }
};


// Add the resize function to the window resize event but put it on a short timer as to not call it too often
var resizeTimer;
$(window).resize(function () {
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(resizeVideo, 150);
});

关于html - 中心全屏背景视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18090595/

相关文章:

javascript - 如果具有特定类的 div 具有 iframe,则将另一个类添加到 div

swift - 使用 Swift 从视频中抓取帧

batch-file - 批量叠加 Logo 到视频文件目录

javascript - 为什么我不能让我的 javascript(石头剪刀布游戏)在我的网站上显示输出?

javascript - 如何使用 jQuery 仅检索隐藏输入上逗号分隔值中的第二项

javascript - carousel-caption 向右移动并占据一半的 carousel

javascript - 如何在 iOS 上自动播放 HTML5 <video> 和 <audio> 标签?

html - 在跨度中换行到下一行的居中文本

javascript - 不支持 Phaser 全屏 Api

html - 如何使用 CSS3 将背景颜色应用于复选框?