添加边距+10每子jQuery

Adding up margin+10 per child jQuery

本文关键字:每子 jQuery 添加      更新时间:2023-09-26

我有一个动态网站,我的客户可以添加块,其中有一个滚动功能,但我需要块来获得margin-top: 10;添加每个类,如:

.li-1 { margin-top:0; }
.li-2 { margin-top: 10px; }
.li-3 { margin-top: 20px }
.li-4 { margin-top: 30px }

这是我的试用代码:http://jsfiddle.net/u8Uj5/8/

使用each循环遍历所有元素,使用index添加元素的边距。

$('div').each(function(i) {
  $(this).css('margin-top', (i * 10) + 'px');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>-------------------------
<h2> I want it like this but then dynamic: </h2>
<div class="s">1</div>
<div class="p">2</div>
<div class="a">3</div>
<div class="n">4</div>

<

jsfiddle演示/strong>

你可以这样做

小提琴例子

$( "div" ).each(function( index ) {
    $(this).css("margin-top", index * 10 + "px")
});

也许你可以试试:

var myMargin = 0; //initial value
$( "div" ).each(function() {
    $(this).css("margin-top", myMargin + "px");
    myMargin += 10; //set your indention whatever you need
});

JSFiddle