making a loop with li elements
I make a script. That cen开发者_StackOverflowter li img items vertical. I have this script:
var imageHeight = $("#main .logolint li img").height();
var hoogteverschil = Math.floor(( 70 - imageHeight ) / 2 );
$("#main .logolint li img").css({ marginTop: hoogteverschil });
But now i have a lot of li items. And this script, give every li items the same margin. How can i change this script? That the script does it for every li item?
you should use the jquery.each() property:
$("#main .logolint li").each(function(){
var img = $(this).find('img');
img.css({ marginTop: Math.floor( (70 - img.height()) / 2) });
});
what the .each() does is basically a for through all the jQUery collection and the $(this) points to the current li in the collection
You can use a simple each() loop:
$("#main .logolint li").each(function() {
var $img = $("img", this);
var hoogteverschil = Math.floor((70 - $img.height()) / 2);
$img.css({ marginTop: hoogteverschil });
});
The css
function accepts a function that can be used to do this without a each
loop:
$("#main .logolint li img").css('margin-top', function(){
return Math.floor(( 70 - $(this).height() ) / 2 );
});
use.......
$("#main .logolint li img").each(function(){
$image = $("img", this);
var hoogteverschil = Math.floor(( 70 - $image.height() ) / 2 );
$image.css({ marginTop: hoogteverschil });
});
精彩评论