动态地为div添加额外的余量

时间:2012-09-26 15:24:20

标签: jquery css

使用jQuery我想在div'foo'中添加额外的上边距,但前提是另一个div'foo2'包含两个以上的图像。

我该怎么做?

4 个答案:

答案 0 :(得分:4)

$('#foo2 > img').length > 2 ? $('#foo').css('margin-top', '10px') : 0;

答案 1 :(得分:2)

if ($('#foo2 img').length>2) $('#foo').css('margin-top', 243);

答案 2 :(得分:1)

我通常喜欢使用addClass()removeClass()(或统一toggleClass()),而不是直接在JS中指定css。它将样式保存在应有的位置。

的jQuery

$('#foo').toggleClass('newClass', $('#foo2 img').length > 2);

CSS

.newClass { margin-top: 10px; ... }

答案 3 :(得分:0)

if ($('#foo2 img').length > 2) {
  $('#foo').css('margin-top', 20);
}