我有以下代码将视频设置为全屏背景。它获取浏览器尺寸并设置纵横比,因此不应该有任何黑条。相反,顶部/底部或侧面溢出,同时仍保持视频居中。 我遇到的问题是如果调整浏览器的大小。它有点工作,但我有一种感觉,如果调整快速发生,脚本不会跟上,导致其中一个边缘出现白色空间。
下面的代码,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);
答案 0 :(得分:0)
只需使用setTime函数即可。
var resizeTimer;
$(window).on('resize', function(e) {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
videoIframe();
}, 250);
});