跳至主要內容
IntersectionObserver

IntersectionObserver

IntersectionObserver 提供了一种异步监听目标元素是否出现在视口的方法,它可以用于判断元素是否可见,从而执行相应的操作。

基本用法

创建 IntersectionObserver 对象

要使用 IntersectionObserver,首先需要创建一个 IntersectionObserver 对象,然后使用该对象来监听目标元素。当目标元素出现在视口或者达到一定阈值时,会触发回调函数,从而执行相应的操作。

const observer = new IntersectionObserver(callback, options);

Yuchen大约 4 分钟JSJSVue
蛇形布局

蛇形布局

实现的效果如下图所示

查看源码

使用 flex 完成 m*n 的布局

首先使用 flex 完成一个简单的 m*n 布局

<template>
  <div class="container">
    <div class="item" v-for="(item, index) in list" :key="index">
      step{{ index + 1 }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";

const list = ref(new Array(12).fill(""));
</script>

<style lang="scss" scoped>
$colNum: 4; // 列数
$rowDistance: 40px; // 行间距
$colDistance: 30px; // 列间距

.container {
  display: flex;
  flex-wrap: wrap;
  gap: $rowDistance $colDistance;

  .item {
    width: calc((100% - $colDistance * ($colNum - 1)) / $colNum);
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: skyblue;
  }
}
</style>

Yuchen大约 9 分钟VueVueSnippets