1
如果有人在之前使用過InDesign,當您將圖像放置在一個框架內時,右鍵單擊該框架將允許您按比例選擇一個填充框選項,框架包含圖像和任何溢出隱藏,然後,您可以中心內容。按比例製作圖像填充div並垂直放置中心圖像
在瀏覽器中如何實現這種效果?
如果有人在之前使用過InDesign,當您將圖像放置在一個框架內時,右鍵單擊該框架將允許您按比例選擇一個填充框選項,框架包含圖像和任何溢出隱藏,然後,您可以中心內容。按比例製作圖像填充div並垂直放置中心圖像
在瀏覽器中如何實現這種效果?
我已經創建fiddle,有助於實現這一結果。
但是,如果div.frame
的寬度大於其圖像的寬度,則會導致圖像的分辨率大於其分辨率。
假設下面的HTML
<div class="frame">
<img src="http://stuffpoint.com/parrots/image/240658-parrots-white-parrot.jpg" />
</div>
這將具有以下樣式施加
.frame {
width: 100%;
height: 200px;
overflow: hidden;
position: relative;
}
.frame img {
width: 100%;
}
強制性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
});
});
}
});
UPDATE : st的替代方式破解上面的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);
});
很好的答案..幫了我很多。 – Paul