<!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>