【问题标题】:giving attributes to all imgs in a div为 div 中的所有 imgs 赋予属性
【发布时间】:2026-01-05 13:45:01
【问题描述】:

我希望 div 中的所有图像都具有一定的边距属性,但我似乎无法让它工作,这是我尝试过的,

$("#images > img").each(function(){
    $(img).css({
      margin-top:15px;
      margin-bottom:15px;
});
});

感谢您的帮助

$("#pt_figures").click(function() {

$('#images').empty();

$('#images').css({
paddingLeft: 150,
paddingRight: 0
});
$('#controls').css({
width:700,
marginLeft:150
});
$('#info').css({
width:660,
marginLeft:150

});

var id = $(this).attr('id');

$("#info_header").load(id +"_header.txt"); $("#content_1").load(id +"_1.txt"); $("#content_2").load(id +"_2.txt"); $("#content_3").load(id +"_3.txt");

$("<img>", { src: "http://www.klossal.com/figures_doc.jpg" }).appendTo("#images"); 
$("<img>", { src: "http://www.klossal.com/figure_front.png" }).appendTo("#images"); 
$("<img>", { src: "http://www.klossal.com/figure_back.jpg" }).appendTo("#images");


$("#images img").addClass("images");

$("#top_section").animate({
    height: 3780
}, 300);
$("#grid").animate({
    marginTop: 3780 + 300,
    paddingBottom: 300
}, 300); 


});

【问题讨论】:

  • 为什么不直接用 CSS 来做呢?
  • 你会怎么用 css 做呢?
  • 请看下面我的回答。
  • 刚刚也实现了,属性应该是marginTop:15,marginBottom:15

标签: jquery children


【解决方案1】:

使用$(this)

 $("#images > img").each(function(){
        $(this).css({
          margin-top:15px;
          margin-bottom:15px;
    });
    });

【讨论】:

    【解决方案2】:

    推荐的做法肯定是添加一个定义所需属性的类,而不是直接在 jQuery 代码中编写 CSS。

    Javascript:

    $("#images img").addClass("myClass");
    

    CSS:

    .myClass {
       margin:15px 0;
    }
    

    或者,只需在 CSS 中定义属性,不要使用 jQuery。

    CSS:

    #images img {
       margin:15px 0;
    }
    

    【讨论】:

    • 我能问一下为什么只是出于好奇而写一个类更好吗?
    • 图片也是动态添加的,通过纯 css 进行的操作似乎由于某种原因没有得到应用,我不知道为什么?
    • 更容易维护样式表,而不是直接在 jQuery 中维护 css。我似乎记得读过它对性能/速度也更好。
    • 您能否在 jsfiddle.net 上重现该问题或提供指向您网站的链接?
    • 知道为什么使用纯 css 对动态添加的内容不起作用?加了javascript后还要绑定吗?
    【解决方案3】:
    $("#images > img").each(function(){
        $(this).css({
          margin-top:15px;
          margin-bottom:15px;
    });
    });
    

    ?

    【讨论】:

      【解决方案4】:

      试试这个:

      $("#images img").each(function(){
          $(this).css({
              margin-top:15px;
              margin-bottom:15px;
          });
      });
      

      您正在使用 $(img) 但它没有上下文。改用 $(this)。此外,如果 IMG 标记不是 DIV 的直接后代,我还从您的选择器中删除了 >。

      【讨论】:

      • 谢谢,人们给出这样的解释总是很棒。我没有意识到 > 有这个含义。
      【解决方案5】:

      这也可以在纯 css 中完成。

      #images > img { // ">" means direct child, remove it if necesarry
        margin: 15px 0; // shorthand for top/bottom: 15px and right/left: 0px
      }
      

      &gt; 表示直接子级,这意味着只有#images 的子级图像会受到影响,“孙子级”和进一步不会。如果您希望他们受到影响,请删除&gt;

      【讨论】:

      • 因此图像是动态添加的,并且通过 css 执行此操作似乎没有得到应用。
      【解决方案6】:

      $(img) 更改为 $(this) 应该很好。

      $(this) 是每个循环中的当前对象。

      你也可以申请$("#images &gt; img").css(...),因为我看不出你为什么需要遍历它们。

      【讨论】: