如何遍历每个图像并设置每个图像的大小?

Tre*_*and 0 jquery

我的下面的代码适用于获取第一个图像的大小,然后添加margin-topmargin-left页面上的每个图像.但是它使用第一张图像作为所有其他图像的基础.我如何循环并使用每个图像的大小来找到它应该用于margin-left和margin-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" });

});
Run Code Online (Sandbox Code Playgroud)

Dav*_*mas 5

你应该使用.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'});
        });
    });
Run Code Online (Sandbox Code Playgroud)

参考文献: