本文實例為大家分享了vue回到頂部監聽滾動事件,供大家參考,具體內容如下
鼠標滾到到頁面中間出現的工具浮框
<template><div class="tools"><ul @mouseleave="mouseLeave()"><li @click="toTop(step)">回到頂部</li><li @mouseover="mouseOver(1)">QQ</li><li @mouseover="mouseOver(2)">微信</li></ul><div v-if="showIndex === 1">玩QQ</div><div v-if="showIndex === 2">玩微信</div></div></template>
<script>export default { name: 'FloatTools', props: { step: { //此數據是控制動畫快慢的 type: Number, default: 50 } }, data() { return { isActive: false, showIndex:0//默認顯示下標 } }, methods: { toTop(i) { //參數i表示間隔的幅度大小,以此來控制速度 document.documentElement.scrollTop -= i; if (document.documentElement.scrollTop > 0) { var c = setTimeout(() => this.toTop(i), 16); } else { clearTimeout(c); } }, handleScroll() { //獲取滾動距頂部的距離,顯示 let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; if (scrollTop > 60) { this.isActive = true; } else { this.isActive = false; } }, mouseOver(index) { //鼠標移到哪個工具上,對應內容顯示出來 this.showIndex = index; }, mouseLeave(){ //鼠標移出工具區域后1秒,內容區域消失 let timer = setTimeout(() => { this.showIndex = 0; clearTimeout(timer) }, 500); } }, mounted: function () { window.addEventListener('scroll', this.handleScroll, true); // 監聽(綁定)滾輪滾動事件 }, destroyed() { window.removeEventListener('scroll', this.handleScroll); //離開頁面需要移除這個監聽的事件 }}</script>
如果遇到scroll一直打印是0,看是否樣式寫了overflow:auto去掉即可;或者給父級撐滿屏幕;
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答