上图是实现的效果
例子:vue3中使用js原生监听滚动条实现导航栏dom元素,使用的vant当中icon图标
<template> <div id="box"> <div id="header"> <van-icon name="wap-nav" size="20" @click="showLeft = true" /> <span v-show="showFont">我的</span> <van-icon name="setting-o" size="20" @click="router.push({ path: '/sestting' })" /> </div> </div> </template> <script setup> let showFont = ref(false)//用来控制"我的"两个字是否显示 //监视滚动条 window.addEventListener('scroll', function (e) { let d = <HTMLElement>document.querySelector('#header') || null if (d == null) return //如果为空则直接返回 if (this.window.scrollY <= 20) { d.style.background = 'none' d.style.color = '#FFFFFF' showFont.value = false } else { d.style.background = '#FFFFFF' d.style.color = '#8F3333' showFont.value = true } }) </script> <style lang="scss" scoped> * { margin: 0px; padding: 0px; } #box { width: 100ch; height: 100vh; background-color: #3e64ff; } #header { width: 100%; height: 8vh; display: flex; padding: 15px; box-sizing: border-box; justify-content: space-between; color: #fff; position: fixed; z-index: 100; top: 0px; } </style>
小萌新一个,第一次分享一下项目当中的小技巧,希望对你有所帮助(大佬轻点喷!!!)