简体   繁体   English

jQuery:如何使用每个函数在div中间分配图像

[英]jQuery: how to allign image in the middle of a div using each function

I have created a script in order to center in the middle all images in a div using the each function. 我创建了一个脚本,以便使用每个函数将div中所有图像的中间居中。 This is the code: 这是代码:

        $('.column').each(function (){

           var colHeight = $(this).innerHeight();
           var colWidth = $(this).width(); 



           var getCenter = (colHeight - imgHeight);            
           var toBeCentered = (getCenter / 2);

           var toReduceWidth = (colWidth - imgWidth);
           var getReducedWidth = (toReduceWidth / 2);      



         $('.myImg').css({'top': toBeCentered + 'px','left': 0});


        });

With the var called toBeCentered I get the height of all divs 使用名为toBeCentered的var,我得到所有div的高度

$('.myImg').css({'top': toBeCentered + 'px','left': 0});

The piece of code above displays always the last one .col div height and not all beginning from the very first. 上面的代码始终显示最后一个.col div高度,而不是所有都从头开始。 How can I set the related div height to the images? 如何设置图像的相关div高度?

You have to do something like: 您必须执行以下操作:

$('.column').each(function (){
    // ...
    $(this).find('.myImg').css({'top': toBeCentered + 'px','left': 0});

});

Because you are setting css attributes for all .myImg objects in every iteration of each function. 因为您要在each函数的每次迭代中为所有.myImg对象设置css属性。 Above solution will work if .myImg objects are in .column class. 如果.myImg对象位于.column类中,则上述解决方案将起作用。

And this is the non-script css solition; 这是非脚本css的选择;

.column{
    display:flex;
    align-items:center;
}
.myImg{
    display: block;
    margin: 0 auto;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM