vue 使用useWindowScroll或 useScroll 实现首页布局中的吸顶效果 并且 对css中&进行解释

141 篇文章 1 订阅
74 篇文章 0 订阅
本文展示了如何利用VueUse库中的`useWindowScroll`功能,创建一个HeaderSticky.vue组件,当页面滚动超过100px时,标题实现吸顶动画。在App.vue中引入该组件,配合CSS样式完成布局,达到预期效果。
摘要由CSDN通过智能技术生成

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>

效果如下:

未吸顶前:

在这里插入图片描述

向下滚动后:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值