监听某个元素滚动,亲测有效
Vue 开发,有时候只需要监听某个元素是否滚动就行了,不需要去监听整个页面。
Vue 有自带的 @scroll 但是并没有什么用,给某个滚动元素加上,滚动该元素并不会调用,加上 CSS 支持滚动样式也一样。
怎么监听呢?通过 addEventListener 与 @mousewheel 配合实现
addEventListener : 增加的是拖拽滚动条也能监听到滚动 @mousewheel :添加的是非拖拽滚动条滚动,比如在元素上鼠标或者触摸板滚动。<template> ? <!-- 滚动视图 --> ? <div class="scrollview" ref="scrollview" @mousewheel="scrollChange"> ? ? <!-- 内容区域 --> ? ? <div class="content"></div> ? </div> </template>
<script> export default { ? mounted () { ? ? // 获取指定元素 ? ? const scrollview = this.$refs['scrollview'] ? ? // 添加滚动监听,该滚动监听了拖拽滚动条 ? ? // 尾部的 true 最好加上,我这边测试没加 true ,拖拽滚动条无法监听到滚动,加上则可以监听到拖拽滚动条滚动回调 ? ? scrollview.addEventListener('scroll', this.scrollChange, true) ? }, ? // beforeDestroy 与 destroyed 里面移除都行 ? beforeDestroy () { ? ? // 获取指定元素 ? ? const scrollview = this.$refs['scrollview'] ? ? // 移除监听 ? ? scrollview.removeEventListener('scroll', this.scrollChange, true) ? }, ? methods: { ? ? // 滚动监听 ? ? scrollChange () { ? ? ? console.log('滚动中') ? ? } ? } } </script>
<style scoped> .scrollview { ? height: 100px; ? overflow-y: auto; ? background-color: yellow; } .content { ? height: 500px; ? background-color: red; } </style>
案例效果
监听dom元素滚动到了可视区?
场景:当某个元素滚动到可视区时,为其添加动画样式(animate.css)。
common/utils.js
export const isElementNotInViewport = function(el) { ?? ?if (el) { ?? ??? ?let rect = el.getBoundingClientRect(); ?? ??? ?return ( ?? ??? ??? ?rect.top >= ?? ??? ??? ??? ?(window.innerHeight || document.documentElement.clientHeight) || ?? ??? ??? ?rect.bottom <= 0 ?? ??? ?); ?? ?} };
在组件内的使用
import { isElementNotInViewport } from "common/utils"; export default { ? ?... ? data() { ? ? return { ? ? ? header_Animate: false ? ? } ? }, ? mounted() { ? ? // 监听滚动事件 ? ? window.addEventListener("scroll", this.scrollToTop); ? }, ? beforeRouteLeave(to, form, next) { ? ? // 离开路由移除滚动事件 ? ? window.removeEventListener('scroll',this.scrollToTop); ? ? next(); ? }, ? methods: { ? ? // 滚动事件 ? ? scrollToTop() { ?? ? ?!isElementNotInViewport(this.$refs.header) ? this.header_Animate = true: ''; ? ? } ? } }
<template> ? <div? ? ? ref="header"? ? ? class="animate__animated"? ? ? :class="{animate__slideInLeft:header_Animate}"> ? </div> </template>
这样就可以控制当dom元素滚动到可视区的时候,给他添加动画样式了。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
查看更多关于Vue实现监听某个元素滚动,亲测有效的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did123638