无限的scss类循环

问题描述 投票:0回答:2

我有这段代码可以生成 5 个项目类

  @for $num from 1 through 5 {
    .item-#{$num} {
      transform-origin: top center;
      animation: rotateX 300ms ($num * 60ms) ease-in-out forwards;
    }
    .item-#{$num} + .item-last {
      transform-origin: top center;
      animation: rotateX 300ms (($num + 1) * 60ms) ease-in-out forwards;
    }
  }

但是如果我创建 6 个或更多项目,它就不起作用..

我怎样才能让它按照我的项目计数而不是常数 5 进行?或者可能是某种不同的方式。

css sass
2个回答
1
投票

对于这样的用例,最好使用 JS。无论您拥有多少个 div(如您想要的那样无限),它都可以使用,但它不会将您的样式表膨胀到无限的文件大小。 我不得不猜测一下你的 HTML 结构。

document.querySelectorAll("[class^='item-']").forEach((item, index) => {
   item.style.animation = `rotateX 300ms ${index * 60}ms ease-in-out forwards`;
   const nextSibling = item.nextElementSibling;
   if(nextSibling){
     nextSibling.style.animation = `rotateX 300ms ${(index + 1) * 60}ms ease-in-out forwards`;
   }
})
[class^=item-] {
      height: 40px;
      width: 40px;
      background: blue;
      transform-origin: top center;
}

.last-item {
      height: 40px;
      width: 40px;
      background: pink;
      transform-origin: top center;
}

@keyframes rotateX {
 0% {
  transform: rotate(0deg);
 }
 
 100% {
  transform: rotate(-90deg);
 }

}
<div class="item-1"></div>
<div class="last-item"></div>
<div class="item-2"></div>
<div class="last-item"></div>
<div class="item-3"></div>
<div class="last-item"></div>
<div class="item-4"></div>
<div class="last-item"></div>
<div class="item-5"></div>
<div class="last-item"></div>


0
投票

您可以使用以下代码来实现类循环:

  @for $num from 1 through 999999 {
    .item-#{$num} {
      transform-origin: top center;
      animation: rotateX 300ms ($num * 60ms) ease-in-out forwards;
    }
    .item-#{$num} + .item-last {
      transform-origin: top center;
      animation: rotateX 300ms (($num + 1) * 60ms) ease-in-out forwards;
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.