开发者

making a loop with li elements

开发者 https://www.devze.com 2023-02-11 10:05 出处:网络
I make a script. That cen开发者_StackOverflowter li img items vertical. I have this script: var imageHeight = $(\"#main .logolint li img\").height();

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 });
});
0

精彩评论

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

关注公众号