封裝了一個小插件模擬fullPage的全屏滾動效果,比較簡單。
特點:
1. 純js實現,小巧輕便。
2. 兼容性好。蘋果、安卓都沒問題,暫時沒遇到問題機型。
缺點:
1. 僅封裝了基礎功能,HTML、css么有去封裝。個人覺得不封裝更方便大家使用。
接下來看看效果圖:
相比效果大家都看到了,接下來看看代碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>移動端滾屏效果</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"> <style type="text/css"> body,html{ width: 100%; height: 100%; margin: 0; padding: 0; } .g-fullPage{ width: 100%; height: 100%; overflow: hidden; } .g-fullPage div{ width: 100%; height: 100%; text-align: center; line-height: 100%; transition: 0.5s ease-in; } .g-fullPage div:nth-child(1){ background-color: #D5F1FD; } .g-fullPage div:nth-child(2){ background-color: aquamarine; } .g-fullPage div:nth-child(3){ background-color: mediumseagreen; } </style> </head> <body> <div class="g-fullPage"> <div class="f-pageFirst">1</div> <div>2</div> <div>3</div> </div> </body> <script type="text/javascript"> /* mainClass 滑動父容器類名 firstClass 第一頁的類名 num 總頁數 */ function fullPage(mainClass, firstClass, num) { var startX = 0, //初始橫坐標 startY = 0, //初始縱坐標 marginTop = 0, //上下滑動變量 touchNum = 0, //上滑極限,是否可以上滑 touchFlag = true, //可滑動標志 true 可滑動,false 不可滑 bodyHeight = document.body.offsetHeight, page = document.getElementsByClassName(mainClass)[0], pageFirst = document.getElementsByClassName(firstClass)[0]; //獲取觸摸的初識坐標 page.addEventListener("touchstart",function(e){ e.preventDefault(); startX = e.targetTouches[0].clientX; startY = e.targetTouches[0].clientY; }) //重置觸摸的坐標值 page.addEventListener("touchend",function(e){ e.preventDefault(); startX = 0; startY = 0; touchFlag = true; }) //監聽並實現 上、下 滑動效果 page.addEventListener("touchmove",function(e){ e.preventDefault(); var newX = e.targetTouches[0].clientX, newY = e.targetTouches[0].clientY; if (newY - startY > 50) { if (touchFlag == true && touchNum > 0) { console.log("下滑"); touchFlag = false; marginTop += 1; touchNum -= 1; pageFirst.style.marginTop = marginTop * bodyHeight+"px"; } } else if (newY - startY < -50) { if (touchFlag == true && marginTop > -num+1) { console.log("上滑"); touchFlag = false; marginTop -= 1; touchNum += 1; pageFirst.style.marginTop = marginTop * bodyHeight+"px"; } } }) } fullPage("g-fullPage", "f-pageFirst",3); </script> </html>
很簡單的一個功能,現在簡略解釋一下代碼:
1. 監聽 touchstart ,獲取觸摸初始坐標; 監聽 touchmove,獲取活動過程中的觸摸點坐標,二者做差. >0 下滑;<0 上滑
2. 當滑動縱坐標差值超過50 ,調節div的 marginTop,顯示不同div內容
這里面有幾個注意點:
1. margin、top等樣式,如果寫在樣式表里,js獲取不到,能取到兼容性也不好。具體原因這里不細說了。但是內聯樣式可以取到。 這里僅做提醒,避免同志們入坑。
2. 記得阻止默認事件。
好啦,個人能力有限,若代碼有問題,希望道友們指出,我們共同學習。 喜歡我的博客的朋友可以關注我,近期會出幾篇 vue2.0+vuex 的博客(react的也會有,具體看時間啦),有需要的可以過來看看吆!