给出以下标记:
<div class="viewport">
<iframe src="youtube.com/blabla"></iframe>
</div>
以下css:
.viewport {
height: 100vh;
width: 100%;
}
iframe {
position: absolute;
}
鉴于以下事实:
是否有可能编写一个脚本,将iframe拉伸到大于父级的大小,以便iframe溢出,隐藏黑条?(是的,我知道它也会裁剪部分内容视频,但没关系)
以下是脚本必须解决的两个示例:
在第一张图片中,黑条位于左侧和右侧。为了解决这个问题,脚本会将iframe拉伸得更宽更高,从而将视频拉伸到内部,直到黑条消失为止。我们丢失了视频的顶部和底部,但没关系。在第二张图片中,黑条位于顶部和底部,我们需要拉伸它并丢失视频的边缘。
这是我的注释尝试,但遗憾的是,代码并未涵盖所有情况。一旦我的视口的宽高比超过~2.1,黑条就会回来。随意废弃我的脚本。
var block = $('.viewport');
var block_h = block.outerHeight();
var block_w = block.outerWidth();
var ratio = block_w / block_h;
// If viewport is landscape (black bars on left/right)
if( ratio >= 1.77777778 ) {
var video_w = (block_h * 16) / 9; // Get width of video within iframe
var total_black_bar_w = block_w - video_w; // Black bar total width
var new_iframe_w = (block_w + total_black_bar_w); // New width of the iframe needed to stretch the video wide enough to hide the black bars
var adjustment_percentage = new_iframe_w / block_w; // If we adjusted the width by 10% for example, then we also need to apply that percentage to the height
var new_iframe_h = (block_h * adjustment_percentage) + 30;
var pull_left = total_black_bar_w / 2; // how far to pull left to center the iframe outside of the parent container
var pull_top = (new_iframe_h - block_h) / 2; // same for top
}
// Portrait viewport (black bars on top/bottom)
else {
var video_h = (block_w * 9) / 16;
var total_black_bar_h = block_h - video_h;
var new_iframe_h = (block_h + total_black_bar_h);
var adjustment_percentage = new_iframe_h / block_h;
var new_iframe_w = (block_w * adjustment_percentage) + 30;
var pull_left = total_black_bar_w / 2;
var pull_top = (new_iframe_h - block_h) / 2;
}
block.find('iframe').css({
'width': new_iframe_w,
'height': new_iframe_h,
'left': '-' + pull_left + 'px',
'top': '-' + pull_top + 'px'
});
答案 0 :(得分:2)
它实际上比你的代码更简单。
始终保持iframe的比例,但只需调整整个事物(实际比例)以填充视口。
使用css定位/变换将其居中。
以下是一个较小视口(带红色边框)的示例,因此您可以看到它的实际效果。
jQuery(function($) {
var viewport = $('.viewport'),
frame = viewport.find('iframe'),
frameRatio = 16 / 9;
$(window).on('resize', function() {
var width = viewport.outerWidth(),
height = viewport.outerHeight(),
ratio = width / height,
targetWidth = width,
targetHeight = height;
if (ratio > frameRatio) {
// viewport is wider than video
// correct the height
targetHeight = width / frameRatio;
} else {
// viewport is taller than video
// correct the width
targetWidth = height * frameRatio;
}
frame.css({
width: targetWidth,
height: targetHeight
});
}).trigger('resize');
});
.viewport {
height: 50vh;
width: 50vw;
position: relative;
border: 1px solid red;
margin: 10% 25%;
}
iframe {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: -1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="viewport">
<iframe src="//www.youtube.com/embed/1La4QzGeaaQ?autoplay=1"></iframe>
</div>
在http://jsfiddle.net/agrxtwn7/embedded/上看到它(转到结果),因为似乎SO阻止了youtube嵌入播放