0

以下代码使用 jQuery。是否可以使用循环创建仅 CSS 版本。我已经看到了显示 DIV 的示例,但每个 DIV 都是单独编码的,带有时间延迟。如果我添加额外的 DIV,此类代码将需要更新 CSS。相反,如果可能的话,我想在 CSS 中使用某种循环。

$("#main-container div").each(function(i) {
  $(this).delay(500 * i).fadeIn(1500);
});
.ig-element {
  width: 200px;
  height: 200px;
  float: left;
  border: 1px solid grey;
  display: none;
  margin: 10px;
  padding: 10px;
  text-align: center;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main-container">

  <div class="ig-element">a</div>
  <div class="ig-element">b</div>
  <div class="ig-element">c</div>

  <div class="ig-element">d</div>
  <div class="ig-element">e</div>
  <div class="ig-element">f</div>

  <div class="ig-element">g</div>
  <div class="ig-element">h</div>
  <div class="ig-element">i</div>

</div>

4

1 回答 1

0

你不能只使用纯 CSS 来做循环。但是,如果您使用 CSS 预处理器(例如 SASS 或 LESS),则可以这样做:

SASS

@for $i from 1 through 9 {
    .#main-container:nth-child(#{$i}n) {
        animation-delay: {$i * 0.5}s;
    }
}

较少的

.mixin-loop (@i) when (@i > 0) {
  // Output the current counter
  .main-container:nth-child(@{i}) {
    animation-delay: {@i * 0.5}s;
  } 
  // The mixin calls itself, recursively
  // until the "@i > 0" condition is no longer met
  .mixin-loop(@i - 1);
}

// Call the mixin with a counter to start the loop
.mixin-loop(9);

您可以在此链接上找到更多方法并了解更多信息。

于 2019-11-01T23:42:45.733 回答