开发者

How to loop through each image and set the size for each individual image?

开发者 https://www.devze.com 2023-04-12 16:57 出处:网络
My code below works fine for getting the size of the first image and then adding margin-top and margin-left to each image on the page. But it\'s using the first image as a basis for all the other imag

My code below works fine for getting the size of the first image and then adding margin-top and margin-left to each image on the page. But it's using the first image as a basis for all the other images. How can I loop through and use the size of each image to find the values it should be using for margin-left and margi开发者_Go百科n-top?

$j(document).ready(function () {

//get the image size:
var theHeight = $j("#co-logo img").height();
var theWidth = $j("#logo img").width();

//place them into the image styles:
$j("#co-logo img").css({ 'margin-top': -theHeight / 2 + "px", 'margin-left': -theWidth / 2 + "px" });

});


You should use .each():

$j(document).ready(
    function(){

    $('#co-logo img').each(
        function(){
            var theWidth = $(this).width();
            var theHeight = $(this).height();

            $(this).css({'margin-top': -theHeight / 2 + 'px', 'margin-left': -theWidth / 2 + 'px'});
        });
    });

References:

  • .each().
0

精彩评论

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