首页 > 解决方案 > 我无法让 .each() 处理我的每个图像

问题描述

请有人可以帮我弄清楚我哪里出错了。

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

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 计算出数字并将其从顶部位置减去,但它似乎只从第一个图像中获取数字并将其应用于所有 3 个图像,当我尝试使用 .each() 我我显然做错了什么,因为它不起作用。

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

任何帮助将不胜感激谢谢

标签: jqueryeach

解决方案


每个.gallery元素只有一个图像。您需要循环遍历.gallery元素:

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

推荐阅读