2014-04-06 23 views
-1

我有一个240x240px div其中包含大小不同的图像的淡出幻灯片。我将每个图像设置为height: 240px,宽度与其高度成比例。有些图像比它们宽(比例)高,所以我把它们集中在div里使用​​这个效果很好,除了溢出的图像的240px div。我怎么能够在div里面溢出的图像居中?我想这(jQuery的),但它并不适用于某种原因,我敢肯定,我想不通工作:如何将约束格内溢出的图像居中

if($("div img").width() > 240) { 
    $(this).css("margin-left", rv); 
    var rv = -1 * ($(this).width()/4) + "px"; 
} 

的逻辑存在,如果图像扩大在宽度div,然后将其转移到左边的是rv px,rv是图像宽度的1/4(因为1/2会将图像剪切成左边一半,所以1/2的1/2有效地居中)?我的第一个猜测是我不能参考$(this),因为我正在尝试,但我不知道。

我知道我可以去添加单独的内联CSS样式,但这很麻烦和平凡。我宁愿有一个脚本可以自动计算图像的中心,然后相应地移动它。有任何想法吗?

回答

1

我建议是这样的:

div.center-img { background:url('/path/img.jpg') center center no-repeat; } 

但你的问题会用这样的回答:

$('div img').each(function() { 
    if(this.width > 240) 
     $(this).css("margin-left", ((this.width - 240)/-2) + "px"); 
}); 
+0

谢谢,第二位帮助过我。 –

1

您可以使用CSS只:

LIVE DEMO

.imgHolder{ 
    border:1px solid #000; 
    width:240px; 
    height:240px; 
    line-height:240px; /* same as element height */ 
    font-size:0;  /* to perfectly vertical align middle the image */ 
    text-align:center; /* to horizontally align middle the image */ 
} 
.imgHolder > img{ 
    max-width:100%; 
    max-height:100%; 
    vertical-align:middle; 
} 
1

遍历图像,当他们已加载获取图像的宽度和父元素宽度比较宽,如果图像的宽度比父图像宽一半,并从左边距减去图像的水平居中。

$("div.centered img").each(function(_,el) { 
    var img = new Image(), 
     parent = $(el).parent(); 

    img.onload = function() { 
     var ma = this.width - $(parent).width(); 
     if (ma > 0) { 
      $(el).css('margin-left', ((ma/2) * -1)); 
     } 
    } 
    img.src = this.src; 
    if (img.complete) img.onload(); 
}); 

FIDDLE