移動端div塊拖動效果程式碼例項

admin發表於2017-02-23
本章節分享一段簡單的程式碼例項。

它實現了移動端拖動div元素隨意移動的效果,並且具有範圍限制。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<!--設定viewport-->
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=0" />
<style>
.div {
  width: 100px;
  height: 100px;
  position: absolute;
  background-color: red;
}
</style>
<script>
window.onload = function () {
  var oDiv = document.getElementsByClassName('div')[0];
  var disX, moveX, L, T, starX, starY, starXEnd, starYEnd;
 
  oDiv.addEventListener('touchstart', function (e) {
    e.preventDefault();//阻止觸控時頁面的滾動,縮放
 
    disX = e.touches[0].clientX - this.offsetLeft;
    disY = e.touches[0].clientY - this.offsetTop;
    //手指按下時的座標
    starX = e.touches[0].clientX;
    starY = e.touches[0].clientY;
    //console.log(disX);
  });
  oDiv.addEventListener('touchmove', function (e) {
    L = e.touches[0].clientX - disX;
    T = e.touches[0].clientY - disY;
    //移動時 當前位置與起始位置之間的差值
    starXEnd = e.touches[0].clientX - starX;
    starYEnd = e.touches[0].clientY - starY;
    //console.log(L);
    if (L < 0) {//限制拖拽的X範圍,不能拖出螢幕
      L = 0;
    }
    else if (L > document.documentElement.clientWidth - this.offsetWidth) {
      L = document.documentElement.clientWidth - this.offsetWidth;
    }
 
    if (T < 0) {//限制拖拽的Y範圍,不能拖出螢幕
      T = 0;
    }
    else if (T > document.documentElement.clientHeight - this.offsetHeight) {
      T = document.documentElement.clientHeight - this.offsetHeight;
    }
    moveX = L + 'px';
    moveY = T + 'px';
 
    this.style.left = moveX;
    this.style.top = moveY;
  });
  window.addEventListener('touchend', function (e) {
    //alert(parseInt(moveX))
    //判斷滑動方向
  });
}
</script>
</head>
<body>
  <div class="div"></div>
</body>
</html>

相關文章