全屏背景视频并保持居中

wou*_*_be 10 javascript css video jquery html5

我正在尝试创建一个网站,我在其中播放一些HTML5背景视频.这一切都很完美,它按照我想要的方式工作.但我也希望将图像保持在屏幕中心,即使用户调整浏览器大小.

<video id="video" src="video/video.mov" type="video/mov" autoplay loop></video>
Run Code Online (Sandbox Code Playgroud)

我得到了这个与一些jQuery,但想知道是否有一个CSS解决方案.

function resizeHandler() {
        // scale the video
        var documentHeight = $(document).height();
        var documentWidth = $(document).width();
        var ratio = $('#video').width() / $('#video').height();

        if((documentWidth / documentHeight) < ratio) {
            $('#video').css({
                'width': 'auto',
                'height': '100%',
                'left': '0px',
                'right': '0px',
                'top': '0px',
                'bottom': '0px'
            })

            var marginRight = $('#video').width() - $(document).width();
            $('#video').css('left', -marginRight);
        } else {
            $('#video').css({
                'width': '100%',
                'height': 'auto',
                'left': '0px',
                'right': '0px',
                'top': '0px',
                'bottom': '0px'
            })

            var marginTop = $('#video').height() - $(document).height();
            $('#video').css('top', -marginTop);
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是我写的jQuery,用于拉伸图像以适应屏幕,并使图像保持居中.不确定这是否可以在CSS中使用,但如果有人知道如何,这可能会很好.

ala*_*747 5

这个问题刚刚被引用到使用css或javascript的100%高度和100%宽度的Place视频

我想我的答案可能就是你要找的那个?

这是代码:

header {
    position: relative;
    height: 100vh;
    z-index: 0;
}
header h1 {
    text-align: center;
    font: 3em/1.4 helvetica neue, helvetica, arial, sans-serif;
    color: #fff
}
header video {
    -webkit-transform: translateX(-50%) translateY(-50%);
    -moz-transform: translateX(-50%) translateY(-50%);
    -ms-transform: translateX(-50%) translateY(-50%);
    -o-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
    position: absolute;
    top: 50%;
    left: 50%;
    min-width: 100%;
    min-height: 100%;
    width: auto;
    height: auto;
    z-index: -100;
}
Run Code Online (Sandbox Code Playgroud)
<header>
    <h1>Sample Title</h1>
	<video autoplay loop class="bg-video">
		<source src="https://d2v9y0dukr6mq2.cloudfront.net/video/preview/abstract-rainbow_wjpctkdes__PM.mp4" type="video/mp4">
	</video>
</header>
Run Code Online (Sandbox Code Playgroud)

这是一个工作小提琴的例子.

希望它能帮助别人:)


ale*_*lex 1

这应该使#video视口的整个大小保持不变,并在用户滚动时保持不变。

#video {
   position: fixed;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但是如何使视频适合浏览器窗口并按比例缩放?我已经使用了相同的 css 代码,但我无法使用 CSS 重新创建我的 jQuery (2认同)