0
:中心,作物,適合視頻背景(iframe中)到下列的裝飾元素的父元素
<div class="viewport">
<iframe src="youtube.com/blabla"></iframe>
</div>
下面CSS:
.viewport {
height: 100vh;
width: 100%;
}
iframe {
position: absolute;
}
並給予下述事實:
- 在iframe中播放的視頻的縱橫比將爲16:9
是否可以編寫一個腳本,將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'
});
哇它工作停止的YouTube嵌入!我不得不刪除z-index:-1,因爲我的特殊佈局,但除此之外它是完美的。非常感謝 – Brian
@Brian,是的,我把-1,所以你可以看到視口的邊界。 –