我无法让.each()处理我的每个图像

问题描述 投票:0回答:1

[请有人帮我弄清楚我要去哪里。

我基本上是试图将图像放在div中,并尝试让jQuery计算出每个图像的高度,然后将其除以2,然后将最终的[[number用于我的CSS像这样Top:calc(50%-number);

https://jsfiddle.net/q3cu92xr/

$(document).ready(tophalfcalcfn); $(window).on('resize',tophalfcalcfn); function tophalfcalcfn() { $('.gallery img').each(function () { var halfImgHeight = parseInt($(".gallery img").height()) / 2; $('.gallery img').css( { top: 'calc(50% - ' + halfImgHeight + 'px)' } ); }); };
    .page {
        text-align: center;
        position: absolute;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        background-color: #eaeaea;
    }
    
    .gallery-outer-row {
        padding: 10px;
        display: inline-block;
        width: 100%;
        background-color: white;
        box-shadow: 0px 0px 10px #0000003b;
        max-width: 780px;
        margin-top: 40px;
    }
    
    .gallery {
        height: 160px;
        width: 31%;
        margin: 0px 1%;
        display: inline-block;
        position: relative;
        float: left;
        overflow: hidden;
    }
    
    .gallery img {
        position: absolute;
        left: 0px;
        max-width: 100%;
        min-height: 100%;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page">
    
       <div class="gallery-outer-row">
        
          <div class="gallery">
              <img src="https://cdn.pixabay.com/photo/2018/08/19/10/16/nature-3616194_960_720.jpg">
          </div>
    
          <div class="gallery">
              <img src="https://images.pexels.com/photos/1366919/pexels-photo-1366919.jpeg?cs=srgb&dl=landscape-photography-of-snowy-mountain-1366919.jpg&fm=jpg">
          </div>
    
          <div class="gallery">
              <img src="https://www.publicdomainpictures.net/pictures/270000/nahled/beautiful-landscape-15304537867Pa.jpg">
          </div>
          
      </div>
      
    </div>
我已经得到jQuery算出数字并将其从顶部位置减去,但是它似乎仅从第一张图片中获取数字并将其应用于所有三个图像中,并且当我尝试使用.each( )我显然在做错事,因为它不起作用。

最后,我知道我可以使用background-size:cover和background-position:50%50%;但在这种情况下,我需要使用HTML img标签。

任何帮助将不胜感激谢谢

jquery each
1个回答
0
投票
每个.gallery元素只有一个图像。您需要改为遍历.gallery元素:

$('.gallery').each(function () { var halfImgHeight = parseInt($(this).children('img').height()) / 2; $(this).children('img').css( { top: 'calc(50% - ' + halfImgHeight + 'px)' } ); });

© www.soinside.com 2019 - 2024. All rights reserved.