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) });
});
精彩评论