2012-03-12 70 views
2

的50%I具有的div X量,都设置到一个特定的高度和宽度。在这些内部是一个图像,大小各不相同。我想找到的图像的高度,除以2,并设置为距顶部值,以便所有图像都在市中心,如果这是有道理的?香港专业教育学院试图使提琴只有即时通讯不知道该如何去做?保证金顶=元件的jQuery

http://jsfiddle.net/R8QUL/1/

回答

6

你可以做这样的事情

$(document).ready(function() { 

    $('.box img').each(function() { 
     var $this = $(this); 
     var parentHeight = $this.parent().height(); 
     var thisHeight = $this.height(); 
     var topmargin = (parentHeight - thisHeight)/2; 
     $this.css("margin-top", topmargin); 
    }); 
}) 

小提琴这里http://jsfiddle.net/R8QUL/6/

+1

这可能是值得指出的是'.innerHeight()'可能工作太,因为这包括'padding',并且这是盒子元素内部的可视部分。根据利亚姆似乎正在尝试做的事情,我想这也许是需要考虑的事情。 – 2012-03-12 11:37:43

2
$(document).ready(function(){ 

    var boxheight = $('.box').height(); 

    $('.box img').each(function(i){ 
      var topmargin = (boxheight - $(this).height())/2 
      $(this).css("margin-top", topmargin); 
    }); 



}) 

直播演示

http://jsfiddle.net/R8QUL/5/

1

这是我会怎么做

$(document).ready(function(){ 
    $('.box img').each(function() { 
     $(this).css("margin-top", $(this).parent().height()/2-$(this).height()/2); 
    }); 
});​ 

FIDDLE

0

有些图像需要一段时间来加载,因此没有宽度或高度呢。要解决这个问题,你可以使用setTimeout。

$(document).ready(function(){ 
    $.each($('.box'), function(){ 
     centerImage($(this)); 
    }); 
}); 

function centerImage(box){ 
    var imgWidth = $(box).find('img').width();  
    var imgHeight = $(box).find('img').height(); 

    if(imgWidth > 0 && imgHeight > 0){ 
     $(box).find('img').css('margin-top', ($(box).height() - imgHeight)/2); 
    } else { 
     setTimeout(function(){ centerImage(box); }, 100); 
    }  
} 

http://jsfiddle.net/7EDSF/

1

如果你有兴趣在纯CSS解决方案:http://jsfiddle.net/R8QUL/11/
只需添加

.box 
    line-height: 225px; 
} 

.box img { 
    display: inline-block; 
    vertical-align: middle; 
} 
+0

现在写我也工作这个解决方案:) – sandeep 2012-03-12 11:53:38