Jquery 使图像按比例填充div,并使图像垂直居中
如果之前有人使用过InDesign,当您将图像放置在框架内时,右键单击框架将允许您选择按比例填充框架选项,使整个框架包含图像,并隐藏任何溢出,然后您可以将内容居中 如何在浏览器中实现此效果 我创建了一个有助于实现此结果的 但是,如果div.frame width大于图像的宽度,则这将导致图像扩展大于其分辨率 假设以下HTMLJquery 使图像按比例填充div,并使图像垂直居中,jquery,css,Jquery,Css,如果之前有人使用过InDesign,当您将图像放置在框架内时,右键单击框架将允许您选择按比例填充框架选项,使整个框架包含图像,并隐藏任何溢出,然后您可以将内容居中 如何在浏览器中实现此效果 我创建了一个有助于实现此结果的 但是,如果div.frame width大于图像的宽度,则这将导致图像扩展大于其分辨率 假设以下HTML <div class="frame"> <img src="http://stuffpoint.com/parrots/image/240658-
<div class="frame">
<img src="http://stuffpoint.com/parrots/image/240658-parrots-white-parrot.jpg" />
</div>
强制jQuery在加载和调整大小时垂直居中图像
$(function(){
centerImageVertically();
$(window).resize(function() {
centerImageVertically();
});
function centerImageVertically() {
var imgframes = $('.frame img');
imgframes.each(function(i){
var imgVRelativeOffset = ($(this).height() - $(this).parent().height()) / 2;
$(this).css({
'position': 'absolute',
'top': imgVRelativeOffset * -1
});
});
}
});
更新:构建上述JavaScript的另一种方法:
$(function () {
var centerImageVertically = function () {
var imgframes = $('.frame img');
imgframes.each(function (i) {
var imgVRelativeOffset = ($(this).height() - $(this).parent().height()) / 2;
$(this).css({
'position': 'absolute',
'top': imgVRelativeOffset * -1
});
});
};
centerImageVertically();
$(window).resize(centerImageVertically);
});
我创建了一个有助于实现此结果的
但是,如果div.frame width大于图像的宽度,则这将导致图像扩展大于其分辨率
假设以下HTML
<div class="frame">
<img src="http://stuffpoint.com/parrots/image/240658-parrots-white-parrot.jpg" />
</div>
强制jQuery在加载和调整大小时垂直居中图像
$(function(){
centerImageVertically();
$(window).resize(function() {
centerImageVertically();
});
function centerImageVertically() {
var imgframes = $('.frame img');
imgframes.each(function(i){
var imgVRelativeOffset = ($(this).height() - $(this).parent().height()) / 2;
$(this).css({
'position': 'absolute',
'top': imgVRelativeOffset * -1
});
});
}
});
更新:构建上述JavaScript的另一种方法:
$(function () {
var centerImageVertically = function () {
var imgframes = $('.frame img');
imgframes.each(function (i) {
var imgVRelativeOffset = ($(this).height() - $(this).parent().height()) / 2;
$(this).css({
'position': 'absolute',
'top': imgVRelativeOffset * -1
});
});
};
centerImageVertically();
$(window).resize(centerImageVertically);
});
回答得很好。。帮了我大忙。回答得很好。。帮了我很多忙。