本章节分享一段简单的代码实例。
它实现了移动端拖动div元素随意移动的效果,并且具有范围限制。

代码实例如下:
   [ 其他 ] 运行代码    下载代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.51qianduan.com/" />
<title>51前端</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>

代码描述:JavaScript 移动端div 拖动效果。JavaScript移动端div拖动效果



210 280



用户评论
大牛,别默默的看了,快登录帮我点评一下吧!:)      登录 | 注册



×
×
51前端

注册

×
绑定手机

请绑定手机号,在继续操作

×
单次下载支付

应付金额:279

支付完成后,回到下载页面,在进行下载

官方QQ群
意见反馈
qq群

扫描上面二维码加微信群

官方QQ群

jQuery/js讨论群
群号:642649996
Css3+Html5讨论群
群号:322131262

加群请备注:从官网了解到