开发中有很多根据滚动来判断的逻辑,这时候最重要的一个步骤就是先判断滚动方向,然后才能进行后续逻辑
我把自己最近项目中用到的代码放在下面(项目用的js和vue版本),各位酌情修改
js版本:
var startY = 0; var that = this; document.addEventListener("touchstart",function(e){ startY = e.changedTouches[0].pageY; },false); document.addEventListener("touchmove",function(e){ var endY = e.changedTouches[0].pageY; var changeVal = endY - startY; if(endY < startY){//向上滑 // alert("向上滑"); }else if(endY > startY){//向下滑 // alert("向下滑"); }else{ // console.log("没有偏移"); } // 获取屏幕高度 },false);
Vue版本:
data() { return { initTop: 0 } } methodds:{ scrollEvent() { // 判断滚动方向 let scrollTop = this.$refs["room"].wrap.scrollTop; let scroll = scrollTop - this.initTop; this.initTop = scrollTop; let dir = "down"; dir = scroll <= 0 ? "up" : "down"; if (dir === "up") { //向上滚动 } else { // 向下滚动 if (scrollTop > 20) { // 判断滚动距离大于20px } } }, }
demo:
<script> var startY = 0;var that = this;var x = document.getElementsByClassName("asd"); window.onload= function(){ document.addEventListener("touchstart",function(e){ startY = e.changedTouches[0].pageY; },false); document.addEventListener("touchmove",function(e){ var endY = e.changedTouches[0].pageY; var changeVal = endY - startY; if(endY < startY){ x[0].style.display="none"; }else if(endY > startY){ x[0].style.display="block"; }},false);} </script>
发表评论 取消回复