通过 jquery 设置 css left for multiple div



嗨,我想在%中为多个div应用css left属性,我将如何做. 我试过下面的代码

.HTML

<div class="inner-nav blue" rel="blue"> 
    <a href="#" style="display: block; left: 0%;">
       Text1 <br>
    </a>
</div>
<div class="inner-nav blue" rel="blue"> 
   <a href="#" style="display: block; left: 0%;">
       Text2 <br>
   </a>
</div>
<div class="inner-nav blue" rel="blue"> 
   <a href="#" style="display: block; left: 0%;">
      Text3 <br>
   </a>
</div>
<div class="inner-nav blue" rel="blue"> 
   <a href="#" style="display: block; left: 0%;">
      Text4 <br>
   </a>
</div>

在 JS 中

$(".inner-nav").each(function(){                                                       
      $(this).find("a:first").css("left", function( index ) {
         var f= index*25;
             f=f+"%";                                                                    
        return  f;
      });         
});

我认为您的问题是锚点的索引,该索引始终0因此0%应用于每个锚点,因此您可以尝试以下操作:

$(".inner-nav").each(function () {
  var idx = $(this).index(); // get the div's index
  $(this).find("a:first").css("left", function (index) {
    var f = idx * 25; // and use it here.
    f = f + "%";
    return f;
  });
});

小提琴


为了简化这一点,您可以使用它:

$(".inner-nav").each(function (idx) {
    $(this).find("a:first").css("left", idx * 25 + "%");
});

代码的问题在于您在错误的位置定义了index。您正在获得正在调用css()元素的index,但它始终是集合中的第一个,因此index将始终为 0:

$(".inner-nav").each(function (index) {
    $(this).find("a:first").css("left", function () {
        var f = index * 25;
        f = f + "%";
        return f;
    });
});

JSFiddle

不需要each()循环。许多 jQuery 方法,包括 css() 句柄循环遍历与选择器匹配的每个元素:

$(".inner-nav").find("a:first").css("left", function( index ) {
    var f= index*25;
    f=f+"%";                                                                    
    return f;
});

JSFiddle

您尚未将索引作为函数属性传递。因此,它没有定义内部循环,索引也是基于0的。因此,第一个div的第一个锚点将剩下0%。试试这个:

 $(".inner-nav").each(function(index){                                                       
                  $(this).find("a:first").css("left",index*25+'%');
 });

工作演示

试试这个

$(".inner-nav").each(function (i) {
    var inn = $(this).index();
    var f = parseInt(inn) * 25;
    var cf = f + "%";
    $(this).find("a:first").css("left", cf);
});

演示

最新更新