Vue實現監(jiān)聽某個元素滾動,親測有效
更新時間:2022年07月27日 10:42:49 作者:卡爾特斯
這篇文章主要介紹了Vue實現監(jiān)聽某個元素滾動,親測有效!具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
監(jiān)聽某個元素滾動,親測有效
Vue 開發(fā),有時候只需要監(jiān)聽某個元素是否滾動就行了,不需要去監(jiān)聽整個頁面。
Vue 有自帶的 @scroll 但是并沒有什么用,給某個滾動元素加上,滾動該元素并不會調用,加上 CSS 支持滾動樣式也一樣。
怎么監(jiān)聽呢?通過 addEventListener 與 @mousewheel 配合實現
addEventListener: 增加的是拖拽滾動條也能監(jiān)聽到滾動@mousewheel:添加的是非拖拽滾動條滾動,比如在元素上鼠標或者觸摸板滾動。
<template> ? <!-- 滾動視圖 --> ? <div class="scrollview" ref="scrollview" @mousewheel="scrollChange"> ? ? <!-- 內容區(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)聽到拖拽滾動條滾動回調
? ? 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ū)?
場景:當某個元素滾動到可視區(qū)時,為其添加動畫樣式(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() {
? ? // 監(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>這樣就可以控制當dom元素滾動到可視區(qū)的時候,給他添加動畫樣式了。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

