<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> *{margin:0;padding:0;} body{height:2000px;} .top{height:100px;width:100%;border:1px solid black;position:fixed;top:0;overflow: hidden;} .main{height: 200px;position: absolute;top:0;width:100%;transition:0.5s;} .box1{height:100px;background: red;width:100%;} .box2{height:100px;background: blue;width:100%;} </style> </head> <body> <div class="top"> <div class="main"> <div class="box1"></div> <div class="box2"></div> </div> </div> <script type="text/javascript"> var main=document.querySelector('.main'); var s,x; document.onscroll=function (){ s=document.documentElement.scrollTop; setTimeout(function (){ x=document.documentElement.scrollTop; },1) if(s<x){main.style.top='-100px'} else{main.style.top='0px'} } </script> </body> </html>
这是一个判断垂直滚动条滚动方向的方法,比较方便,代码量很少。
方法原理:当页面滚动的时候西安获取滚动高度s,一毫秒之后再获取一次滚动高度x,
此时进行判断,如果x大于s,证明向下滚动,反之则是向上滚动,拿走不谢!