代码之家  ›  专栏  ›  技术社区  ›  Sireini

更改每个子元素的顶部样式

  •  0
  • Sireini  · 技术社区  · 6 年前

    我有一个DIV,它有一个子类,这些子类将根据用户的选择而变化。我正在循环这些元素,并使用jquery更改顶部位置,如下所示:

    var top = 0;
    
    $('.shareBtn').each(function(index, item) {
      top += 66;    
      console.log(top, item, index);
    
      $(item).eq(index).css("top", top + "px");
    })
    

    然而,这只是附加 top: 66px 到第一个元素。如何附加顶部样式 +66px 每件物品?

    从评论中我发现我的问题不够清楚。我想增加66px每个循环计数的项目。

    因此,如果循环索引为0,1,2,我希望看到这样的顶部样式:

    <div class="shareBtn" style="top: 0;"></div>
    <div class="shareBtn" style="top: 66px;"></div>
    <div class="shareBtn" style="top: 132px;"></div>
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Gavin Thomas    6 年前

    你已经打电话了 .each() -当你对它进行索引时,你的目标是一个。

    var top = 0;
    
    $('.shareBtn').each(function(index, item){
      top += 66;
    
      console.log(top, item, index);
    
      $(this).css("top", top + "px");
    })
    

    https://jsfiddle.net/47fdz9mc/