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  为了更平滑的返回顶部

路由跳转页面:

在不同路由切换的时候,可以自动滚动到页面的顶部,而不是停留在原先的位置

 

 路由配置部分:

// 创建路由器
const router = createRouter({
  history: routerHistory,
  routes: routes,
  scrollBehavior() {
    return {
      top: 0,
    };
  },
});
export default router;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值