1、首先安装@vueuse/core
npm i @vueuse/core -s
2、新建一个HeaderSticky.vue文件,其内容为;
<template>
<div class="app-header-sticky" :class="{show:y>=100}">
<div class="container" v-show="y>=100">模拟title</div>
</div>
</template>
<script setup>
import { useWindowScroll } from '@vueuse/core'
import {watch} from "vue";
const { y } = useWindowScroll()
watch(y, (newVal)=>{
console.log(y.value)
},{immediate:true})
</script>
<style scoped lang="less">
.app-header-sticky{
width: 100%;
height: 100px;
position: fixed;
left: 0;
top: 0;
z-index: 999;
background-color: pink;
transform: translateY(-100%);
opacity: 0;
&.show {
transition: all 0.3s linear;
transform: none;
opacity: 1;
}
.container {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
font-size: 20px;
}
}
</style>
3、在App.vue中写如下内容:
<template>
<div class="body">
<div class="header">模拟title</div>
<HeaderSticky></HeaderSticky>
<div class="container">
</div>
</div>
</template>
<script setup>
import {ref} from "vue";
import HeaderSticky from './components/HeaderSticky.vue'
</script>
<style scoped lang="less">
.header{
height: 100px;
text-align: center;
line-height: 100px;
font-size: 20px;
background-color: pink;
}
.container{
height: 1000px;
background-color: lightgrey;
}
</style>
4、效果如下:
当鼠标滑动到100px时会出现吸顶动画
方式二
<script setup>
import { useScroll } from '@vueuse/core'
const { y } = useScroll(window)
</script>
<template>
<div class="boxTop">
</div>
<div class="testUl" :class="{show: y>72}" >
<div><a href="">测试1</a></div>
<div><a href="">测试2</a></div>
<div><a href="">测试3</a></div>
</div>
<div class="box"></div>
</template>
<style scoped lang='scss'>
.boxTop{
height: 80px;
background-color: green;
}
.testUl{
width: 100%;
height: 80px;
position: fixed;
left: 0;
top: 0;
z-index: 999;
background-color: pink;
border-bottom: 1px solid #e4e4e4;
// 此处为关键样式!!!
// 状态一:往上平移自身高度 + 完全透明
transform: translateY(-100%);
opacity: 0;
// 状态二:移除平移 + 完全不透明
&.show { // &表示同级别的
transition: all 0.3s linear;
transform: none;
opacity: 1;
}
}
// 这样写可以完全替代 &.show 这种写法,效果是一样的
//.show { // &表示同级别的
// transition: all 0.3s linear;
// transform: none;
// opacity: 1;
//}
.box{
height: 1000px;
}
</style>