vue3页面吸顶的开发

1、使用js监听window滚动变化

<script setup>
import { onMounted, ref, watch } from "vue";
onMounted(() => {
  window.addEventListener("scroll", scrollToTop);
});
let scrollTop = ref("0");
const scrollToTop = () => {
  // let app = document.querySelector(".app-header");
  // console.log(app.offsetTop);
  // console.log(document.documentElement.scrollTop);
  scrollTop.value = document.documentElement.scrollTop;
};
watch(scrollTop, (newv) => {
  let ghgh = document.querySelector(".app-header-sticky");
  console.log(newv);
  if (newv > 100) {
    ghgh.classList.add("show");
  } else {
    ghgh.classList.remove("show");
  }
});
</script>

提前定义好一个变量存储页面滚动卷去的高度,然后用watch监听数值的变化,再给吸顶组件的盒子增加或者溢出类名,可实现吸顶效果

 tips:

 要获取当前页面的滚动条纵坐标位置,用: document.documentElement.scrollTop; 而不是: document.body.scrollTop; documentElement 对应的是 html 标签,而 body 对应的是 body 标签

 document.body.scrollTop与document.documentElement.scrollTop两者有个特点,就是同时只会有一个值生效。比如document.body.scrollTop能取到值的时候,document.documentElement.scrollTop就会始终为0;反之亦然。所以,如果要得到网页的真正的scrollTop值,可以这样:

var scrollTop=document.body.scrollTop+document.documentElement.scrollTop;

这两个值总会有一个恒为0,所以不用担心会对真正的scrollTop造成影响。一点小技巧,但很实用。

css:

.app-header-sticky {
  width: 100%;
  height: 80px;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  background-color: #fff;
  border-bottom: 1px solid #e4e4e4;
  // 此处为关键样式!!!
  // 状态一:往上平移自身高度 + 完全透明
  transform: translateY(-100%);
  opacity: 0;

  // 状态二:移除平移 + 完全不透明
  &.show {
    transition: all 0.3s linear;
    transform: none;
    opacity: 1;
  }

 2、使用插件获取页面卷去高度

插件:  vueuse

安装: npm i @vueuse/core

 搜索 :   useScroll方法

 使用:    

<script setup lang="ts">
import { useScroll } from '@vueuse/core'

const el = ref<HTMLElement | null>(null)
const { x, y, isScrolling, arrivedState, directions } = useScroll(el)
</script>

<template>
  <div ref="el"></div>
</template>

 这里的 el 是获取 想要得到的卷去高度的元素     这里我写的是window

<script setup>
import { onMounted, watch } from "vue";
import { useScroll } from "@vueuse/core";
const { y } = useScroll(window);
watch(y, (newValue, oldValue) => {
  let ghgh = document.querySelector(".app-header-sticky");
  if (newValue > 100) {
    ghgh.classList.add("show");
  } else {
    ghgh.classList.remove("show");
  }
});
</script>

扩展:

返回顶部:

<button @click="fgfg">返回顶部</button>




const fgfg = () => {
  window.scrollTo({
    top: 0,
    behavior: "smooth",
  });
};

smooth  为了更平滑的返回顶部

猜你喜欢

转载自blog.csdn.net/m0_70547044/article/details/132423553