Vue實(shí)現(xiàn)監(jiān)聽某個(gè)元素滾動,親測有效
監(jiān)聽某個(gè)元素滾動,親測有效
Vue 開發(fā),有時(shí)候只需要監(jiān)聽某個(gè)元素是否滾動就行了,不需要去監(jiān)聽整個(gè)頁面。
Vue 有自帶的 @scroll 但是并沒有什么用,給某個(gè)滾動元素加上,滾動該元素并不會調(diào)用,加上 CSS 支持滾動樣式也一樣。
怎么監(jiān)聽呢?通過 addEventListener 與 @mousewheel 配合實(shí)現(xiàn)
addEventListener: 增加的是拖拽滾動條也能監(jiān)聽到滾動@mousewheel:添加的是非拖拽滾動條滾動,比如在元素上鼠標(biāo)或者觸摸板滾動。
<template> ? <!-- 滾動視圖 --> ? <div class="scrollview" ref="scrollview" @mousewheel="scrollChange"> ? ? <!-- 內(nèi)容區(qū)域 --> ? ? <div class="content"></div> ? </div> </template>
<script>
export default {
? mounted () {
? ? // 獲取指定元素
? ? const scrollview = this.$refs['scrollview']
? ? // 添加滾動監(jiān)聽,該滾動監(jiān)聽了拖拽滾動條
? ? // 尾部的 true 最好加上,我這邊測試沒加 true ,拖拽滾動條無法監(jiān)聽到滾動,加上則可以監(jiān)聽到拖拽滾動條滾動回調(diào)
? ? scrollview.addEventListener('scroll', this.scrollChange, true)
? },
? // beforeDestroy 與 destroyed 里面移除都行
? beforeDestroy () {
? ? // 獲取指定元素
? ? const scrollview = this.$refs['scrollview']
? ? // 移除監(jiān)聽
? ? scrollview.removeEventListener('scroll', this.scrollChange, true)
? },
? methods: {
? ? // 滾動監(jiān)聽
? ? scrollChange () {
? ? ? console.log('滾動中')
? ? }
? }
}
</script><style scoped>
.scrollview {
? height: 100px;
? overflow-y: auto;
? background-color: yellow;
}
.content {
? height: 500px;
? background-color: red;
}
</style>案例效果

監(jiān)聽dom元素滾動到了可視區(qū)?
場景:當(dāng)某個(gè)元素滾動到可視區(qū)時(shí),為其添加動畫樣式(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
?? ??? ?);
?? ?}
};在組件內(nèi)的使用
import { isElementNotInViewport } from "common/utils";
export default {
? ?...
? data() {
? ? return {
? ? ? header_Animate: false
? ? }
? },
? mounted() {
? ? // 監(jiān)聽滾動事件
? ? 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>這樣就可以控制當(dāng)dom元素滾動到可視區(qū)的時(shí)候,給他添加動畫樣式了。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
VUE+Element實(shí)現(xiàn)增刪改查的示例源碼
這篇文章主要介紹了VUE+Element實(shí)現(xiàn)增刪改查的示例源碼,幫助大家更好的理解和使用vue,感興趣的朋友可以了解下2020-11-11
vue?cli3配置image-webpack-loader方式
這篇文章主要介紹了vue?cli3配置image-webpack-loader方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07

