将HTML视频的大小调整为一致的大小

时间:2018-03-12 19:27:46

标签: javascript html css resize html5-video

我正在尝试调整视频大小,以便在所有屏幕尺寸上保持相同的方面。目前,如果我调整屏幕大小,它会缩小盒子,它将失去我想要的大小。我的目标是让视频在屏幕尺寸方面保持相同的宽度和高度。

这是我在调整窗口大小时尝试对视频执行的操作的示例:

enter image description here

目前,这是我的JavaScript寻找收集所有视频然后迭代它们以计算方面的方式:

resizeVideo() {
    let windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
        windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    let windowAspectRatio = windowHeight / windowWidth;
    // Get each video
    let videos = document.getElementsByTagName('video');

    // iterate through each video to resize and keep the same aspect
    for (let i = 0; i < videos.length; i++) {
        let video = videos[i];
        let videoWidth = video.videoWidth;
        let videoHeight = video.videoHeight;
        let videoAspectRatio = videoHeight / videoWidth;

        console.log(video.width + " " + video.height);
        console.log(windowHeight + " " + windowWidth);

        // compare window height vs window width
        if (windowHeight < windowWidth) {
            // window height is less than window width
            video.width = window.innerWidth * .95;
        } else {
            // window height it greater than window width
            video.height = window.innerHeight * .95;
        }

    }
}

这是关于我如何构建HTML的CSS:

.carousel { // carousel will be 100% width and height
    width: 100%;
    height: 100%;

    .carousel-content { // Content
        display: block;

        .project { // Each project will take up 100% of the screen
            position: relative;
            width: 100%;
            height: 100vh;

            .video-container { // Container will contain video
                width: 100%;
                height: 100%;


                video { // Calculate video width, and height with javascript
                    display: block;
                    margin: auto;
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

填充是可行的方法,因为垂直填充是基于宽度计算的,因此您可以使用它来创建一致的比率。

设置为父容器 - &gt;调整容器大小 - &gt;绝对  定位视频,高度和宽度均为100%。

(查看代码示例全屏测试)

&#13;
&#13;
#VideoOuter {
  padding: 20px;
  border: 1px solid black;
 }
.sizing-div {
  width: 100%;
  padding-bottom: 33%;
  height: 0;
  font-size: 0;
  position: relative;
 }
 #Video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: aliceblue;
font-size: 20px;
 }
&#13;
<div id="VideoOuter">
  <div class="sizing-div">
    <div id="Video" class="constant-ratio">I'm a video</div>
  </div>
</div>
&#13;
&#13;
&#13;