vue判断滚动条上下拉及是否在顶部

方式1. 使用useScroll方式

bash 复制代码
import { useScroll } from '@vueuse/core'
setup() {
    const showNaviBar = ref(true)
    const { arrivedState } = useScroll(document.querySelector('.body'), {
      onScroll: (e) => {
        console.log(arrivedState.top, arrivedState.bottom)
        if (arrivedState.top) {// 在顶部
          showNaviBar.value = true
          return
        }
        if (arrivedState.bottom) {// 到底
          showNaviBar.value = false
        } else {
          showNaviBar.value = true// 其它情况..
        }
      },
    })
    return {
    	showNaviBar,
	}
 }

方式2. 直接监听dom的scroll事件

bash 复制代码
import { ref, onBeforeUnmount, onMounted } from '@vue/composition-api'
setup() {
    const showNaviBar = ref(true)
    const scrollNum = ref(0)
    const handleScroll = (e) => {
      const scrollElement = e.target
      const scrollTop = scrollElement.scrollTop
      const scroll = scrollTop - scrollNum.value
      scrollNum.value = scrollTop
      console.log(scrollTop, scroll)
      if (scrollTop === 0) {// 在顶部,不滚动的情况
        showNaviBar.value = false
        return
      }
      if (scroll >= 0) { // 在滚动时,向下
        showNaviBar.value = false
      } else {// 在滚动时,向上
        showNaviBar.value = true
      }
    }
    onMounted(() => {  
      const scrollElement = document.querySelector('.body')
      scrollElement.addEventListener('scroll', handleScroll)
    })
    onBeforeUnmount(() => {  
      const scrollElement = document.querySelector('.body')
      scrollElement.removeEventListener('scroll', handleScroll)
      showNaviBar.value = true
    })
    return {
    	showNaviBar,
	}
 }
bash 复制代码
handleScroll 打印日志: down
2582 23
2601 19
2614 13
2623 2
handleScroll 打印日志: up
2787 -13
2773 -14
2728 -8
2724 -4
相关推荐
kerli几秒前
Compose 组件:LazyColumn 核心参数与 key/contentType 详解
android·前端
好运的阿财1 分钟前
“锟斤拷”问题——程序中用powershell执行命令出现中文乱码的解决办法
linux·前端·人工智能·机器学习·架构·编辑器·vim
踩着两条虫12 分钟前
VTJ.PRO AI + 低代码实战:接入高德地图
前端·vue.js·ai编程
绝世唐门三哥13 分钟前
React性能优化:memo、useMemo和useCallback全解析
前端·react.js·memo
兔子零102415 分钟前
Claude Code 都把宠物养进终端了,我做了一个真正能长期玩的中文宠物游戏
前端·游戏·游戏开发
xiaotao13116 分钟前
Vite 与 Webpack 开发/打包时环境变量对比
前端·vue.js·webpack
摆烂工程师21 分钟前
教你如何查询 Codex 最新额度是多少,以及 ChatGPT Pro、Plus、Business 最新额度变化
前端·后端·ai编程
捧月华如24 分钟前
响应式设计原理与实践:适配多端设备的前端秘籍
前端·前端框架·json
笨笨狗吞噬者26 分钟前
VSCode 插件推荐 Copy Filename Pro,快速复制文件、目录和路径的首选
前端·visual studio code
web_小码农26 分钟前
CSS 3D动画 旋转木马示例(带弧度支持手动拖动)
javascript·css·3d