Со временем я действительно улучшил ответ @TrueBlueAussie и подумал, что опубликую здесь более сложный ответ для дальнейшего использования.
Сделал его плагином на GitHub здесь: https://github.com/drewbaker/fitToParent< /сильный>
Вот плагин jQuery:
jQuery.fn.fitToParent = function (options) {
this.each(function () {
// Cache the resize element
var $el = jQuery(this);
// Get size parent (box to fit element in)
var $box;
if( $el.closest('.size-parent').length ) {
$box = $el.closest('.size-parent');
} else {
$box = $el.parent();
}
// These are the defaults.
var settings = jQuery.extend({
height_offset: 0,
width_offset: 0,
box_height: $box.height(),
box_width: $box.width(),
}, options );
// Setup box and element widths
var width = $el.width();
var height = $el.height();
var parentWidth = settings.box_width - settings.width_offset;
var parentHeight = settings.box_height - settings.height_offset;
// Maintin aspect ratio
var aspect = width / height;
var parentAspect = parentWidth / parentHeight;
// Resize to fit box
if (aspect > parentAspect) {
newWidth = parentWidth;
newHeight = (newWidth / aspect);
} else {
newHeight = parentHeight;
newWidth = newHeight * aspect;
}
// Set new size of element
$el.width(newWidth);
$el.height(newHeight);
});
};
Итак, если у вас есть HTML этого:
<div id="wrapper">
<iframe width="720" height="405" src="//player.vimeo.com/video/19223989"></iframe>
</div>
Самый простой способ вызвать плагин выглядит так:
jQuery('#wrapper iframe').fitToParent();
Но я часто устанавливаю #wrapper близко к высоте и ширине окна, например:
// Get window height and width
var winHeight = jQuery(window).height();
var winWidth = jQuery(window).width();
// Set wrapper height/width to that of window
jQuery('#wrapper').height(winHeight).width(winWidth);
// Size Iframe
jQuery('#wrapper iframe').fitToParent({
height_offset: 100, // Put some space around the video
width_offset: 100, // Put some space around the video
});
Вы также можете ввести пользовательский размер поля, чтобы он соответствовал элементу, например:
// Get window height and width
var winHeight = jQuery(window).height();
var winWidth = jQuery(window).width();
// Size element
jQuery('#wrapper iframe').fitToParent({
height_offset: 100, // Put some space around the video
width_offset: 100, // Put some space around the video
box_height: winHeight, // Force use of this box size
box_width: winWidth // Force use of this box size
});
Я также добавил возможность установить класс CSS «size-parent» для родительского элемента, и затем он будет использовать этот родительский элемент для размера поля. Полный пример этого:
// HTML like this
<div id="wrapper" class="size-parent">
<div class="media">
<iframe width="720" height="405" src="//player.vimeo.com/video/19223989"></iframe>
</div>
</div>
// jQuery like this
jQuery('.media iframe').fitToParent();
Если вы не установите .size-parent, он вернется к родительскому элементу. Если вы установите параметр box_height/box_width, то они явно переопределяют все.
Теперь, чтобы показать, насколько мощным это может быть, попробуйте это для правильного соотношения сторон по вертикали и горизонтали по центру iFrame!
// CSS like this
#wrapper {
text-align: center;
display: table-cell;
vertical-align: middle;
}
#wrapper iframe {
display: inline-block;
}
// HTML like this
<div id="wrapper" class="size-wrapper">
<iframe width="720" height="405" src="//player.vimeo.com/video/19223989"></iframe>
</div>
// jQuery like this
// Get window height and width
var winHeight = jQuery(window).height();
var winWidth = jQuery(window).width();
// Size wrapper
jQuery('#wrapper').height( winHeight ).width( winWidth );
// Size element
jQuery('#wrapper iframe').fitToParent({
height_offset: 200, // Put some space around the video
width_offset: 200, // Put some space around the video
});
// Fit iFrame to wrapper
jQuery('#wrapper iframe').fitToParent();
В реальной жизни я оборачиваю jQuery в функцию, а затем вызываю эту функцию при изменении размера окна для действительно отзывчивых iFrames!
person
Drew Baker
schedule
09.08.2014