保证金最高=元素jQuery的50%

时间:2012-03-12 11:00:25

标签: jquery css

我有X个div,都设置为特定的高度和宽度。其中有一张图片,大小各不相同。我想找到图像的高度,将其除以2并将其设置为边距最高值,以便所有图像都在中心,如果这有意义的话?我试过制作一个小提琴只是我不确定如何去做...

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

5 个答案:

答案 0 :(得分: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 :(得分: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/

答案 2 :(得分:1)

以下是我将如何做到这一点

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

FIDDLE

答案 3 :(得分:1)

如果您对纯css解决方案感兴趣:http://jsfiddle.net/R8QUL/11/
只需添加

.box
    line-height: 225px;
}

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

答案 4 :(得分: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/

相关问题