移动端页面顶部滑动实现菜单的弹出与隐藏
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> <style> .outer-scroll { position: relative; } .top-box { width: 100%; background: #666; display: none; padding: 10px; } .scroll-box { width: 100%; height: 1000px; top: 0; background: #ccc; position: absolute; padding: 10px; } </style> </head> <body> <div class="outer-scroll"> <div class="top-box"> <h4>This is top menu</h4> <h4>It will be show after touch down</h4> <h4>It will be hidden after touch up</h4> </div> <div class="scroll-box"> <h1>page layout</h1> <h1>page layout</h1> <h1>page layout</h1> <h1>page layout</h1> </div> </div> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script> let scroll = document.querySelector('.scroll-box'); let outer_scroll = document.querySelector('.outer-scroll'); let topbox = document.querySelector('.top-box'); let topboxHeight; let touchStart; let touchDis; // 注意如果绑定触摸时的事件则会在下拉时从手指的下拉位置开始下拉 该事件在手指触摸屏幕时候触发,即使已经有一个手指放在屏幕上也会触发。 scroll.ontouchstart = function (event) { touchStart = 0; touchDis = 0; // 说明:由于手指头是多点触摸到屏幕上的我们所以e.originalEvent.targetTouches的 // 意思是一个手指触碰点集合我们只需要获取第一个点就可以了所以 touchStart = event.targetTouches[0].pageY; }; // 当手指在屏幕上滑动的时候连续地触发。在这个事件发生期间,调用preventDefault()事件可以阻止滚动。 scroll.ontouchmove = function (event) { // 顶部上下拖拽 let touchPos = event.targetTouches[0].pageY; touchDis = touchPos - touchStart; if (document.documentElement.scrollTop == 0 && touchDis > 0) { topbox.style.display = 'block'; } if (!topboxHeight) { topboxHeight = topbox.offsetHeight; } if (touchDis >= 0) { $(scroll).stop().animate({top: topboxHeight}, 'fast'); } else { if (topbox.style.display == 'block') { $(scroll).stop().animate({top: '0'}, 'fast'); event.preventDefault(); } } }; </script> </body> </html>