替换图片背景与视频背景

时间:2015-07-08 20:25:22

标签: html5 css3 html5-video

在保留所有属性的同时,用视频背景替换我目前拥有的图片背景的最快方法是什么?

到目前为止,这是我的代码:

<div id="hero">
<div id="bg"></div>
<table id="outerDiv" cellpadding="0" cellspacing="0" border="0">
    <tr>
        <td valign="middle" id="innerDiv">
<div class="post-header"><img src="http://www.makemeapro.org/wp-content/uploads/2015/07/logo.png" style="max-width:100%;height:auto;"></div>
<div class="post-header"><h1 style="color: #383838;">Helping young professionals navigate the world of work.</h1></div>
<div align="center"><button class="btn">JOIN THE REVOLUTION</button></div>
        </td>
    </tr>
</table>
</div>

JsFiddle:http://jsfiddle.net/zxqz7oe0/

1 个答案:

答案 0 :(得分:1)

用视频替换图片背景的一种快捷方法是将视频放在该图片的顶部,并使用object-fit覆盖父图像区域。它需要次要的HTML和CSS更改:

HTML:

<div id="bg">
     <video autoplay loop>
          <source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4"/>
          <source src="http://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg"/>
     </video>
</div>

CSS:

#hero video {
  width:100%;
  height:100%;
  object-fit:cover; /* Resize the video to cover parent, like a background-size:cover */
}

#hero #bg {
  /* The styles for #bg remain the same, you'd just need to add */
  /* one more, so the video that overflows the #hero is hidden: */
  overflow:hidden; 
}

您可以看到一个处理此JSFiddle的示例:http://jsfiddle.net/zxqz7oe0/1/

此解决方案的一个问题是尚未完全支持object-fit:Chrome,Firefox和Android都可以,但您可能在Firefox和移动设备上遇到问题。 IE根本不支持它。 (你可以see the browser support here。)

您可以使用这种简单的方法,然后为不支持object-fit的浏览器提供JavaScript后备解决方案。知道视频大小后,可以很容易地计算窗口加载/调整大小时每个时刻所需的宽度/高度。