VueUse - 获取页面卷去的高度(滚动条滚动的距离) - useScroll

1,387 阅读1分钟

函数名

  • useScroll
  • 函数作用:
    • 响应式获取滚动位置和状态;

参数

  • el
    • 基于哪个 元素 滚动;
      • el 是滚动元素的父级;
    • 可以是元素的 ref 属性值;
    • 也可以是 window

使用:

<script setup>
import { ref } from "vue";
import { useScroll } from "@vueuse/core";

const el = ref(null);
// const { x, y } = useScroll(window);
const { x, y } = useScroll(el);
</script>

<template>
  <div class="text">
    <span>水平滚动距离:{{ x }}</span>
    <span>垂直滚动距离:{{ y }}</span>
  </div>
  <div class="scroll1" ref="el">
    <div class="son"></div>
  </div>
  <div class="scroll"></div>
</template>

<style>
.text {
  position: fixed;
  top: 0;
  left: 0;
  width: 300px;
  height: 200px;
  background-color: #3fb17c;
}

.scroll1 {
  width: 500px;
  height: 500px;
  overflow: auto;
  border: 1px solid #333;
}

.scroll1 .son {
  width: 1000px;
  height: 1000px;
}

.scroll {
  width: 200vh;
  height: 1200px;
}
</style>
  • 参数为 elimage.png

  • 参数为 windowimage.png