原生js仿寫手機端下拉刷新
更新時間:2021年08月18日 14:13:12 作者:前端挖掘機
這篇文章主要為大家詳細介紹了原生js仿寫手機端下拉刷新,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了js仿寫手機端下拉刷新的具體代碼,供大家參考,具體內容如下
話不多說先看效果圖:
當下拉小于40px時顯示文字:
當下拉大于40px時現實文字
松開時顯示文字
實現原理
<div class="content"> <div class="left"></div> <div class="top"> <p id="p"></p> <div id="buttom"> </div> </div> </div>
CSS:
<style> * { margin: 0; padding: 0; box-sizing: border-box; } .content { width: 350px; height: 600px; position: relative; margin: 0 auto; } .top { width: 100%; height: 100%; background-color: #ccc; border: 12px solid black; border-radius: 10px; overflow: hidden; margin-top: 50px; border-top: 35px solid black; } #buttom { width: 100%; height: 100%; background-color: rgb(47, 196, 47); position: relative; padding: 10px; border-top: 2px solid red; } #p { display: inline-block; height: 30px; width: 100%; text-align: center; line-height: 30px; color: rgb(2, 2, 2); font-size: 15px; position: absolute; top: 40px; left: 0; display: none; } .left { height: 10px; width: 100px; background-color: #ccc; position: absolute; top: 12px; left: 110px; border-radius: 5px; } .left::after { display: inline-block; content: ""; width: 15px; height: 15px; background-color: #ccc; border-radius: 50%; position: absolute; left: 120px; top: -2px; } </style>
JS:
<script> var but = document.getElementById("buttom"); var p = document.getElementById("p"); var moveY = 0 //初始化按下時的位置 var tops = 0; //初始化tops。tops為下拉的距離 but.onmousedown = function(e) { //鼠標按下事件 moveY = e.offsetY //獲取鼠標按下時Y軸的位置 but.onmousemove = function(e) { //鼠標移動事件 p.innerHTML = "下拉刷新" p.style.display = "block"; //鼠標移動時現實提升文字并且讓文字為“下拉刷新” tops = e.offsetY - moveY //tops大小為鼠標Y軸移動的距離減去按下時的距離 if (tops < 0) { tops = 0 //阻止上拉 } else if (tops > 40) { //tops大于40時提示可以松開鼠標馬上刷新 p.innerHTML = "松開立刻刷新" } this.style.top = tops + 'px'; //讓元素相對定位的top值等于tops的值 // console.log(tops) } but.onmouseup = function() { //鼠標松開事件 but.onmousemove = null //清空鼠標移動事件,阻止元素繼續(xù)跟著鼠標移動 if (tops < 40) { //如果下拉距離b不足40px的話,元素馬上復位不進行刷新,并且提示文字消失 this.style.top = 0; p.style.display = "none" } else { //如果下拉距離大于40px提示正在刷新 p.innerHTML = "正 在 刷 新 . . ." setTimeout(() => { //延遲1.3秒后復位,這里做的只是模仿,實際項目需要在重新請求數據成功后復位 tops = 0 this.style.top = tops; p.style.display = "none" }, 1300); } } } </script>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
javascript實現的textarea運行框效果代碼 不用指定id批量指定
今天在寫一個網頁的時候用到了N多嵌套在textarea標簽里的代碼,定義雙擊運行其內的代碼段。但是每次創(chuàng)建一個這樣的可運行的實例都要給textarea元素自定義一個id值和寫入雙擊事件,好不麻煩。2009-12-12Object.keys() 和 Object.getOwnPropertyNames() 的區(qū)別詳解
這篇文章主要介紹了Object.keys() 和 Object.getOwnPropertyNames() 的區(qū)別詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05微信 jssdk 簽名錯誤invalid signature的解決方法
這篇文章主要介紹了微信 jssdk 簽名錯誤invalid signature的解決方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01