代码之家  ›  专栏  ›  技术社区  ›  Brett Williams

当设备上不允许自动播放时,用背景图像替换背景视频[复制]

  •  0
  • Brett Williams  · 技术社区  · 6 年前

    有一个自动播放的背景图像,我正试图找出如何在不允许自动播放的设备上用图像替换它。这个 <video> tag 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 回复  |  直到 6 年前
        1
  •  1
  •   dave    6 年前

    第一 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 ,这可能很棘手。