jquery更改特定div内的图像边距

时间:2013-05-31 21:36:21

标签: javascript jquery css image margin

这是我的代码:

html

<html>
<body>
  <div id="id">
    <div class="one">
      <img>
    </div>
    <div class="two">
      <img>
    </div>
    <div class="one">
      <img>
    </div>
  </div>
</body>
</html>

我想仅在div class =“one”中更改图像边距 这是我的jquery代码:

$(document).ready(function() {                  
  $(".one").each(function(){
        $("img").css("margin-top", 10 "px");
  });
});

此代码最终会更改所有图像边距,...帮助!

1 个答案:

答案 0 :(得分:4)

您的选择器$("img")所有图像匹配,因此会css重复应用div.one,每个$(document).ready(function() { $(".one img").css("margin-top", "10px"); }); 一次。试试这个:

10 "px"

(我也将"10px"更改为$(".one img"),但我认为这是问题中的拼写错误。)

img使用后代选择器来匹配作为类"one"的元素后代的所有>元素。

如果您只想匹配直接子项(如示例标记),请改用$(document).ready(function() { $(".one > img").css("margin-top", "10px"); // ^--- change is here });

{{1}}

有关选择器的更多信息:

相关问题