在设备上不允许自动播放时,用背景图像替换背景视频

时间:2018-03-30 17:19:02

标签: javascript html css html5-video bootstrap-4

有一个自动播放背景图像,我试图找出如何用不允许自动播放的设备上的图像替换它。 <video>标签POSTER元素似乎工作正常,但它似乎也在我的iPhone上,它不允许自动播放视频,即使它根本没用,它仍会下载视频。有更好的解决方案吗?

(自动播放检测帖是答案的一部分,但我的问题有点不同,我在下面标出了答案。)

#video-bg {
  position: relative;
  width: auto;
  min-width: 100%;
  height: auto;
  background: transparent url(video-bg.jpg) no-repeat;
  background-size: cover;
	display: block;
}
video {
  display: block;
}

.video-container {
  width: 100%;
  max-height: 550px;
  overflow: hidden;
  position: static;
  top: 0;
  right: 0;
  z-index: -100;
}
.overlay-desc {
  background: rgba(0,0,0,0);
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div id="top-banner-vid" class="container-fluid px-0">
  <div class="row no-gutters video-container">
    <div class="col">
      <video class="embed-responsive video-bg" poster="12-sunrise-picture.jpg" autoplay loop muted>
        <source class="embed-responsive-item" src="http://www.icutpeople.com/wp-content/themes/icutpeople/assets/video/waynesworld.mp4" type="video/mp4">
        Your browser does not support the video tag. Please update your browser to enjoy the full features of this website. </video>
      <div class="container overlay-desc">
        <h1>Wayne's World</h1>
      </div>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

首先,detect if autoplay is supported,然后:

$(function() {
    let $container = $('#top-banner-vid .video-container > .col');
    let $video = $.parseHTML('<video class="embed-responsive video-bg" poster="12-sunrise-picture.jpg" autoplay loop muted><source class="embed-responsive-item" src="http://www.icutpeople.com/wp-content/themes/icutpeople/assets/video/waynesworld.mp4" type="video/mp4">Your browser does not support the video tag. Please update your browser to enjoy the full features of this website.</video>');
    let $image = $.parseHTML('<img src="12-sunrise-picture.jpg"/>');

    function addVideo() {
        $container.append($video);
    }

    function addImage() {
        $container.append($image);
        $image.on('click', () => {
            $container.empty().append($video);
        });
    }

    if (autoplaySupported()) {
        addVideo();
    } else {
        addImage();
    }
}();

当然,一旦加载,他们就必须再次点击它,所以你可能会想尝试use the click event to also start the video,这可能很棘手。