关键性代码如下:
var scroll = document.documentElement.scrollTop || document.body.scrollTop; //获取屏幕距离顶部的距离
.js // 下述方法是引入mui+vue的案例 ,展示代码为methods里面的方法
init:function(){ doc.addEventListener("scroll",function(){ // 实时监听,如果是ios需要做300ms延迟,否则点击索引的时候,对象距离顶部的高度不够,会出现闪动的效果,体验感不佳 if(!noScroll){ var appealDo = vm.$el.querySelector("#appealDo").offsetTop- 45; //获取#appealDo距离顶部的距离 var appealComm = vm.$el.querySelector("#appealComm").offsetTop- 45; //获取#appealComm距离顶部的距离 var scrollTop = doc.body.scrollTop || doc.documentElement.scrollTop; //获取屏幕距离顶部的距离 if(scrollTop <= appealDo){ vm.activeIdx = 0; // activeIdx 是表示高亮,用作顶栏菜单 }else if(scrollTop > appealDo && scrollTop <= appealComm){ vm.activeIdx = 1; }else if(scrollTop > appealComm){ vm.activeIdx = 2; } } noScroll = false; }); }, toggleTypes:function(idx){ noScroll = true; if (vm.activeIdx != idx) { if (idx === 0) { doc.body.scrollTop = 0; doc.documentElement.scrollTop = 0; }else if(idx === 1){ vm.$nextTick(function(){ doTop = vm.$el.querySelector("#appealDo").offsetTop - 45; doc.body.scrollTop = doTop; doc.documentElement.scrollTop = doTop; }); }else{ vm.$nextTick(function(){ doTop = vm.$el.querySelector("#appealComm").offsetTop - 45; doc.body.scrollTop = doTop; doc.documentElement.scrollTop = doTop; }); } vm.activeIdx = idx; } },
在VUE脚手架的项目里面可以这样操作,下述案例实现的是做高度监听控制顶部菜单的透明度变化
mounted() { window.addEventListener('scroll', this.menu) }, methods: { menu() { this.scroll = document.documentElement.scrollTop || document.body.scrollTop; var opacity = this.scroll / 44; if (opacity <= 1) { this.$nextTick(() => { this.opacity = opacity }); } else { this.opacity = 1 } } }