# 下拉刷新功能 ## Pull to Refresh animation ###### tags : `w3HexSchool` . `js` > 在手機中 , 常見的下拉刷新功能 , 在 WEB 上要如何做出來呢 ? ![](https://i.imgur.com/MiNEh8V.gif) :::info 手指在螢幕上輕點 , 觸發 touchstart 事件 手指在螢幕上滑動 , 觸發 touchmove 事件 手指離開螢幕 , 觸發 touchend 事件 監聽上方 3 種不同的事件 , 再利用 event.targetTouches[0].screenX 取得目前手指的位置 ::: :::warning 備註:下拉功能僅在手機上有效 ::: 開始滑動時 ( touchstart ) , 我們取得起始座標值 pStart = ( startX , startY ) ```javascript= document.addEventListener('touchstart', e => swipeStart(e), false); ``` 從 touchstart 中的 `event.targetTouches[0].screenX` 取得 startX 且 `event.targetTouches[0].screenY` 取得 startY ```javascript= function swipeStart(event){ if( event.targetTouches ){ const startX = event.targetTouches[0].screenX; const startY = event.targetTouches[0].screenY; pStart = { x : startX , y : startY }; } } ``` 滑動途中 ( touchmove ) , 我們取得現在座標值 pCurrent = ( currentX , currentY ) ```javascript= document.addEventListener('touchmove', e => swipe(e), false); ``` 從 touchmove 中的 `event.targetTouches[0].screenX` 取得 currentX 且 `event.targetTouches[0].screenY` 取得 currentY ```javascript= function swipe(event){ if( event.targetTouches ){ const currentX = event.targetTouches[0].screenX; const currentY = event.targetTouches[0].screenY; pCurrent = { x : currentX , y : currentY }; } } ``` 算出滑動的距離 ( pCurrent - pStart ) 決定螢幕下拉多少 px 更新 main 元素的 `translateY` 產生 main 元素被向下拉的動畫 ```javascript= let changeY = (pCurrent.y - pStart.y); main.style.transform = `translateY(${changeY}px)`; ``` 結束滑動時 ( touchend ) ```javascript= document.addEventListener('touchend', e => swipeEnd(e), false); ``` 停止滑動後 , 立即歸位 ```javascript= function swipeEnd(event){ main.style.transform = 'translateY(-100px)'; } ``` ==成果== <iframe height="265" style="width: 100%;" scrolling="no" title="pull-to-refresh-easy" src="https://codepen.io/andrew781026/embed/MWKdpzX?height=265&theme-id=light&default-tab=js,result" frameborder="no" allowtransparency="true" allowfullscreen="true"> See the Pen <a href='https://codepen.io/andrew781026/pen/MWKdpzX'>pull-to-refresh-easy</a> by 王澍 (<a href='https://codepen.io/andrew781026'>@andrew781026</a>) on <a href='https://codepen.io'>CodePen</a>. </iframe> ## 美化後的成果 <iframe height="265" style="width: 100%;" scrolling="no" title="pull-to-refresh" src="https://codepen.io/andrew781026/embed/zYrXLqZ?height=265&theme-id=light&default-tab=js,result" frameborder="no" allowtransparency="true" allowfullscreen="true"> See the Pen <a href='https://codepen.io/andrew781026/pen/zYrXLqZ'>pull-to-refresh</a> by 王澍 (<a href='https://codepen.io/andrew781026'>@andrew781026</a>) on <a href='https://codepen.io'>CodePen</a>. </iframe> #### 開發小貼士 可用 chrome 的 debug mode 在你的筆電測試此下拉效果 ![](https://i.imgur.com/ZwXeUst.png) ## 參考資料 - [Pull to refresh animation with Vanilla JavaScript](https://dev.to/vijitail/pull-to-refresh-animation-with-vanilla-javascript-17oc)