javascript - 调整大小时的全屏背景视频宽高比

标签 javascript jquery html css video

我有以下代码将视频设置为全屏背景。它获取浏览器尺寸并设置宽高比,因此不应有任何黑条。相反,顶部/底部或侧面溢出,同时仍保持视频居中。 我遇到的问题是浏览器是否调整大小。它有点有效,但我有一种感觉,如果调整大小发生得很快,脚本就跟不上,导致沿其中一个边缘出现空白。

代码如下,jsfiddle在这里: https://jsfiddle.net/RobertCS/r50ktjoh/2/

<div class="bgvideo">
    <iframe src="https://player.vimeo.com/video/75542539?background=1&loop=1&title=0&byline=0&portrait=0&autoplay=1&badge=0" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen frameborder="0"></iframe>
</div>
body, html {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
}

.bgvideo {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    z-index: 1;
}

.bgvideo iframe {
    position: absolute;
}
function videoIframe() {
    //Get the browser dimensions and calculate aspect ratio
    var browswerWidth = $(window).width();
    var browswerHeight = $(window).height();
    var aspectRatio = browswerHeight / browswerWidth;

    if (aspectRatio < 0.5625) {
        //Video too tall for viewport.
        //Set the video width to the browser width
        //Set height according to aspect ratio.
        //Finally, offset top/bottom to keep video centred.

        var newHeight = 0.5625 * browswerWidth;
        $('.bgvideo iframe').css({
            'width': browswerWidth + 'px'
        });
        $('.bgvideo iframe').css({
            'height': newHeight + 'px'
        });
        $('.bgvideo iframe').css({
            'bottom': -((newHeight - browswerHeight) / 2) + 'px'
        });
    } else {

        //Video too wide for viewport.
        //Set the video height to the browser height
        //Set width according to aspect ratio.
        //Finally, offset left/right to keep video centred.

        var newWidth = browswerHeight / 0.5625;
        $('.bgvideo iframe').css({
            'width': newWidth + 'px'
        });
        $('.bgvideo iframe').css({
            'height': browswerHeight + 'px'
        });
        $('.bgvideo iframe').css({
            'left': -((newWidth - browswerWidth) / 2) + 'px'
        });
    };
};
$(window).resize(videoIframe);
$(document).ready(videoIframe);

最佳答案

只需使用 setTime 函数即可完成。

var resizeTimer;
$(window).on('resize', function(e) {
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(function() {
    videoIframe();
  }, 250);
});

关于javascript - 调整大小时的全屏背景视频宽高比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37897216/

相关文章:

javascript - 动画卷轴有很多问题

javascript - 如何在具有 z 索引的 div 内的列表项上触发 mouseenter(或任何鼠标)事件?

html - 将文本与 HTML 中的图像对齐到行的底部

javascript - 单击时向右和向左滑动 div

javascript - 无法将单击事件添加到创建对象后才创建的按钮

javascript - document.getElementById 的值是多少?

javascript - 如何在 jquery 中从多个选择器创建对象?

javascript - Webpack 版本 5.1.2 "MainTemplate.hooks.startup has been removed"出错

javascript - 如何在jquery函数中插入值?

javascript - 如何在jquery中的if else条件中使字段成为必填字段