gpt4 book ai didi

jquery - 在javascript中计算以克服垂直对齐:middle

转载 作者:太空宇宙 更新时间:2023-11-04 03:22:46 27 4
gpt4 key购买 nike

我正在尝试编写一个函数来

  1. 找到图片的高度
  2. 执行计算(200px - 图片高度)
  3. 为每个不同的缩略图添加一个 css 样式(.imgk{margin-top:"calculated value";})。

我无法为 margin-top 设置一个固定值,因为图像大小不同。它们被放置在一个单独的 div 中,我已将 max-widthmax-height 设置为 200x200 像素。我想如果我可以计算并将 css 添加到每个图像。

注意:我试图克服vertical-align:middle,因为div 是display:block。 (对于 display:table-cell,垂直对齐有效,但 image(div) 不会更改行以适合窗口。)

这就是我现在拥有的,chrome 说“img”未定义?

<div id="container_imgk">
<div><a href="image-1.jpg"><img src="image-1.jpg" class="imgk"></a></div>
<div><a href="image-2.jpg"><img src="image-2.jpg" class="imgk"></a></div>
</div>

<script>
var img_th = 0;//define the variable to 0 for each new image?

if ($("img").hasClass('imgk')) {//only apply the follow to img with class imgk
var img_th = $((200-$("img").height())/2);//the caluation
$("img").css('margin-top',img_th);//add css to class imgk
});
</script>

非常感谢。

最佳答案

使用

$('img.imgk').each(function(){
var self = $(this),
height = self.height();

self.css({
'margin-top': (200 - height)/2
});
});

关于jquery - 在javascript中计算以克服垂直对齐:middle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27637583/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com