標籤:移動 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 });
這個方法便是我解決滑動不了的問題,再此與大家分享一下下,如果還有其他更好的方法來解決這個問題,還請各位大神留言,多多指教!
關於移動端的滑動無效的問題