使用SCSS实现随机大小的方块在页面滚动

发布于:2025-05-30 ⋅ 阅读:(19) ⋅ 点赞:(0)

目录

一、scss中的插值语法

二、方块在界面上滚动的动画


一、scss中的插值语法

插值语法 #{}‌ 是一种动态注入变量或表达式到选择器、属性名、属性值等位置的机制

.类名:nth-child(n) 表示需同时满足为父元素的第n个元素且类名为给定条件 

 效果图:

<div class="parent">
    <div class="child2"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
  </div>
//nth是针对父元素下所有子元素进行选择
$height: 400px; // 视口高度
.parent {
  width: 400px;
  height: #{$height}; // 背景容器高度为视口高度
  .child {
    width: 50px;
    height: 50px;
    background-color: pink;
    margin: 10px;
  }
  .child2 {
    width: 30px;
    height: 30px;
  }
  //表示类名为.child2且为parent的第一个元素
  .child2:nth-child(1) {
    background-color: #6dd5ed; // 白色背景,透明度0.05
  }
  @for $i from 2 through 4 {
    //父元素所有子元素的1-4
    :nth-child(#{$i}) {
      background-color: red; // 白色背景,透明度0.05
    }
  }
}

二、方块在界面上滚动的动画

示例图:

方块滚动

<div class="main">
  <div class="bg-container">
    <ng-container *ngFor="let item of countList">
      <div class="square"></div>
    </ng-container>
  </div>
</div>
// 基础配置
$bg-color: #ffd6e7; // 粉色背景
$square-count: 40; // 方块数量
$min-size: 2vmin; // 最小尺寸
$max-size: 10vmin; // 最大尺寸
$animation-duration: 20s; // 基础动画时长

//背景方块
.main {
  width: 100%;
  height: 100%;
  // 容器样式
  .bg-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
}

// 方块基础样式
.square {
  position: absolute;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 10%;
  animation: float linear infinite;
  background: linear-gradient(to bottom, #ee9ca7, #ffdde1);
  opacity: 0;

  // 生成随机方块 random随机生成0-给定数值的随机数,左闭右开
  @for $i from 1 through $square-count {
    &:nth-child(#{$i}) {
      $size: random($max-size - $min-size) + $min-size;
      $delay: random(30) * 0.1s;
      $duration: 15 + random(20) * 0.1s;
      $startX: random(50) * 1vw;
      $endX: $startX + (random(40) - 20) * 1vw;
      $rotation: random(360) * 1deg;

      width: #{$size};
      height: #{$size};
      animation-delay: $delay;
      animation-duration: $duration;
      left: $startX;

      @keyframes float {
        0% {
          transform: translateY(110vh) rotate(0deg);
          opacity: 0;
        }
        10% {
          opacity: 0.7;
        }
        50% {
          opacity: 1;
        }
        90% {
          opacity: 0.7;
        }
        100% {
          transform: translateY(-10vh) translateX($endX) rotate($rotation);
          opacity: 0;
        }
      }
    }
  }
}


网站公告

今日签到

点亮在社区的每一天
去签到