注:瀏覽器f12,選擇移動方式查看。html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; touch-action: none; } html, body { width: 100%; height: 100%; } #div1 { width: 100px; height: 100px; background: cyan; position: absolute; bottom: 200px; right: 100px; } </style> </head> <body> <div id="div1"></div> </body> </html> <script> window.onload = function () { // var moveNode = document.querySelector(".cus"); // moveNode.style.transform = 'translateX(400px)'; var div1 = document.querySelector("#div1"); //限制最大寬高,不讓滑塊出去 debugger var maxW = document.body.clientWidth - div1.offsetWidth; var maxH = document.body.clientHeight - div1.offsetHeight - 100; var moveDirection = 0; //自動移動方向:+ 右移:- 左移 var moveDistance = 100; //自動移動距離 //手指觸摸開始,記錄div的初始位置 div1.addEventListener('touchstart', function (e) { // if(div1.style.transition != ''){ // div1.style.transition = ''; // div1.style.transform = ''; // let direc = moveDirection == '+' ? '-' : '+'; // direc += moveDistance - 0; // div1.style.left = ((div1.style.left + '').replace(/px/, '') - 0 + parseFloat(direc)) + 'px'; // } var ev = e || window.event; var touch = ev.targetTouches[0]; oL = touch.clientX - div1.offsetLeft; oT = touch.clientY - div1.offsetTop; document.addEventListener("touchmove", defaultEvent, false); }); //觸摸中的,位置記錄 div1.addEventListener('touchmove', function (e) { var ev = e || window.event; var touch = ev.targetTouches[0]; var oLeft = touch.clientX - oL; var oTop = touch.clientY - oT; if (oLeft < 0) { oLeft = 0; } else if (oLeft >= maxW) { oLeft = maxW; } if (oTop < 0) { oTop = 0; } else if (oTop >= maxH) { oTop = maxH; } div1.style.opacity = '0.2' div1.style.left = oLeft + 'px'; div1.style.top = oTop + 'px'; }); //觸摸結束時的處理 div1.addEventListener('touchend', function () { div1.style.opacity = '1' moveDirection = div1.style.left.replace(/px/, '') - 0 + div1.offsetWidth / 2 > document.body.clientWidth / 2 ? '+' : '-'; moveDistance = moveDistance; if(moveDirection == '+'){ moveDistance = document.body.clientWidth - div1.style.left.replace(/px/, '') - div1.offsetWidth; }else{ moveDistance = div1.style.left.replace(/px/, '') } if(moveDistance > 0){ div1.style.transition = 'all .5s'; div1.style.transform = 'translateX(' + moveDirection + moveDistance + 'px)'; setTimeout(function() { div1.style.left = div1.style.left.replace(/px/, '') - 0 + (moveDirection == '-' ? -moveDistance : moveDistance) + 'px' div1.style.transition = ''; div1.style.transform = ''; }, 500) } document.removeEventListener("touchmove", defaultEvent); }); //阻止默認事件 function defaultEvent(e) { e.preventDefault(); } // var ele = document.querySelector(".father"); // left_scroll(ele); } </script>
效果圖:瀏覽器