开发者

jquery each loop to work out correct vertical margins

i am trying to make jquery calculate the height of the parent then the child then calculate the correct margins to apply to the children.

The calculations work fine, just that it is not looping for each child of the loop;

var navHeight = $('#nav').height();
var navImgHeight = $('#nav li 开发者_如何学Pythonimg').height();

$('#nav li img').each(function(){

    $(this).css({ "margin-top" : ((navHeight - navImgHeight) / 2) });

});


It is because in your example you are defining navImgHeight once, when you need to define it for each image (see the for each?):

var navHeight = $('#nav').height();

$('#nav li img').each(function(){
    var navImgHeight = $(this).height();
    $(this).css({ "margin-top" : ((navHeight - navImgHeight) / 2) });
});


.height() returns a number but no specified unit, like px or em. You will need to add that to the script.

You will need to do something like this (untested)

$(this).css({ "margin-top" : ((navHeight - navImgHeight) / 2) + "px" });


Try this

var navHeight = $('#nav').height();
var navImgHeight;

$('#nav li img').each(function(){
   navImgHeight = $(this).height();
    $(this).css({ "margin-top" : ((navHeight - navImgHeight) / 2) });

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜