0

HTML:

<ul>
  <li><img src="image1.png" /></li>
  <li><img src="image2.png" /></li>
  <li><img src="image3.png" /></li>
  <li><img src="image4.png" /></li>
  <li><img src="image5.png" /></li>
  <li><img src="image6.png" /></li>
</ul>

...图像大小不同,我想将它们垂直居中。

jQuery:

$('ul li').css('paddingTop', height($("ul li").height() - ("li img") / (2)));
# padding-top = height of li - height of image / 2

..但这不起作用。

4

3 回答 3

6

更好的方法?

如果您使用的是 jQuery,为什么不使用其中一个居中插件呢?

// make sure li in this case is position:relative;
$("ul li img").center();

目前的问题

以下行有很多问题:

height($("ul li").height() - ("li img") / (2))

height()不是一个函数,除非你在别处声明了它。如果是这样,它到底应该做什么?注意,我不是指$.height()jQuery 框架中的有效方法。此外,("li img")不是数值,因此将其除以 2 没有任何意义。

也许以下内容可能更有帮助:

$("ul li img").each(function(){
  var pHeight = $(this).parent().height();
  var iHeight = $(this).height();
  var diff    = Math.round(pHeight - iHeight);
  $(this).parent().css("paddingTop", diff);
});
于 2009-12-29T17:47:27.053 回答
2

我认为@Jonathan 的答案是你应该遵循的( centering plugin ),但这里是你的代码清理了很多:

$('ul li').each(function(){
   var $li = $(this), $img = $li.find('img');
   $img.css('padding-top', ($li.height() / 2) - ($img.height() / 2));
});

Of course, this will only work when the li has a fixed height in the CSS.

于 2009-12-29T17:57:57.513 回答
1

Vertically center

$('ul li img').each(function(){
  var height=$(this).outerHeight(),
  li=$(this).closest('li'),
  li_height=li.outerHeight();
  li.height(li_height+'px');
  $(this).css({marginTop: (li_height-height)/2+'px'});
});
于 2009-12-29T18:01:58.003 回答