關於移動端的滑動無效的問題

來源:互聯網
上載者:User

標籤:移動   client   中間   css   分析   dem   star   沒有   tor   

  之前遇到這樣一個問題,自己寫的那部分在自己的電腦和所有手機上都是ok的,但是當吧這個部分和同時的那部分合到一起的時候,出現了一個問題,那便是曾經設定overflow:auto的部分無法滑動,原本以為是兩個人的代碼出現了衝突,可是檢查過後並不是這個原因,經過尋找之後,再分析overfolw:auto盒子的高度、添加-webkit-overflow-scrolling:touch都沒有用,一直到後來便用了移動端的touch的三個事件來解決這個滑動不了的問題。

  這邊僅僅用一個小的demo來解說一下touch的三個事件:

HTML代碼:

 1 <div class="box"> 2   <ul> 3     <li>hehe99</li> 4     <li>hehe88</li> 5     <li>hehe77</li> 6     <li>hehe66</li> 7     <li>hehe55</li> 8     <li>hehe44</li> 9     <li>hehe333</li>10     <li>hehe22</li>11     <li>hehe11</li>12   </ul>13 </div>

css代碼:

 1 * { 2   margin: 0; 3   padding: 0; 4   list-style: none; 5 } 6  7 .box { 8   margin: 100px auto; 9   height: 300px;10   width: 100px;11   overflow: hidden;12   border: 1px solid #ccc;13   -webkit-overflow-scrolling: touch;14 }15 16 li {17   height: 50px;18   background-color: pink;19   border: 1px solid #000;20   text-align: center;21   line-height: 50px;22 }

js代碼:

 1 var ul = document.querySelector("ul"); 2 var box = document.querySelector(".box"); 3  4 var startY = null;  //手指初始位置 5 var centerY = 0;  //中間值centerY 6 var maxdown = 50;   //最大向下滑動距離 7 var maxup = -(ul.offsetHeight - box.offsetHeight + 50);  //最大向上滑動距離 8 var maxupfantan = 0;  //向上反彈設定值 9 var maxdownfantan = -(ul.offsetHeight - box.offsetHeight);  //向下反彈設定值10 ul.addEventListener("touchstart", function (e) {11   startY = e.changedTouches[0].clientY;12 13 });14 ul.addEventListener("touchmove", function (e) {15   var dy = e.changedTouches[0].clientY - startY;16   var temp = centerY + dy;17   if (temp < maxup) {18     temp = maxup;    //向上滑19   } else if (temp > maxdown) {20     temp = maxdown;  //向下滑21   }22   ul.style.transition = "none";23   ul.style.transform = "translateY(" + temp + "px)";24 });25 26 ul.addEventListener("touchend", function (e) {27   var dy = e.changedTouches[0].clientY - startY;28   centerY = centerY + dy;29   if (centerY > maxupfantan) {30     centerY = maxupfantan;  //一定要注意改變centerY的值,否則會出現回不去的問題31     ul.style.transition = "transform 0.5s";32     ul.style.transform = "translateY(" + maxupfantan + "px)";33   } else if (centerY < maxdownfantan) {34     centerY = maxdownfantan;35     ul.style.transition = "transform 0.5s";36     ul.style.transform = "translateY(" + maxdownfantan + "px)";37   }38 });

  這個方法便是我解決滑動不了的問題,再此與大家分享一下下,如果還有其他更好的方法來解決這個問題,還請各位大神留言,多多指教!

關於移動端的滑動無效的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.