在列表中隐藏距离超过3步的兄弟姐妹的最简洁的方法是什么?

What's the neatest way to hide siblings more than three steps away in a list?

本文关键字:兄弟姐妹 简洁 方法 是什么 3步 列表 隐藏 距离      更新时间:2023-09-26

我有一个元素列表要移动,每次一个是活动的。

我现在是这样做的:

$('.cards li:eq('+ step +')').animate(//animation info)
$('.cards li:eq('+ (step + 1) +'), .cards li:eq('+ (step - 1) +')').animate({'opacity':'0.8'})
$('.cards li:eq('+ (step + 2) +'), .cards li:eq('+ (step - 2) +')').animate({'opacity':'0.6'})
$('.cards li:eq('+ (step + 3) +'), .cards li:eq('+ (step - 3) +')').animate({'opacity':'0.4'})

对于活动项和三对等距相邻的兄弟姐妹来说,这很有效。我需要的是,虽然,是使列表项4个地方或更多有自己的动画。

我正在这样做,它工作了:

  $('.cards li').each(function(){
      thisEq = $(this).index() + 1
      if(thisEq > step && ((thisEq - step) > 3)){animate({'opacity':'0'})}
      if(thisEq < step && ((step - thisEq) > 4)){animate({'opacity':'0'}}
    })

但是有没有更干净的方法呢?

您可以使用每个参数:

  $('.cards li').each(function(i){
     if(i - step == 0){
       $(this).animate()
     }else if( Math.abs(i-step) < 4){
       // 1, 2, 3       
       $(this).animate({'opacity': 1 - 0.2 * Math.abs(i-step)})
     }else{
       // 4 and more
     }
  }