请有人帮我弄清楚我要去哪里。
我基本上是在尝试将图像放入div中,并尝试让jQuery计算出每个图像的高度,然后将其除以2,然后是最后的 number < / strong>会像这样在我的CSS中使用顶部: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标签。
任何帮助将不胜感激 谢谢
答案 0 :(得分:3)
每个.gallery
元素只有一个图像。您需要改为遍历.gallery
元素:
$('.gallery').each(function () {
var halfImgHeight = parseInt($(this).children('img').height()) / 2;
$(this).children('img').css( { top: 'calc(50% - ' + halfImgHeight + 'px)' } );
});
答案 1 :(得分:0)
您可以像这样在每个函数中使用参数简化代码:
function tophalfcalcfn() {
$('.gallery img').each(function (i, img) {
var halfImgHeight = parseInt($(img).height()) / 2;
$(img).css( { top: 'calc(50% - ' + halfImgHeight + 'px)' } );
});
};