富贵资源网 Design By www.hznty.com

本文实例为大家分享了js实现适配移动端的拖动效果,供大家参考,具体内容如下

1.html

<div id="div1">
 <div id="div2"></div>
</div>

2.js

var flag = false;
var cur = {
 x: 0,
 y: 0
 }
 var nx, ny, dx, dy, x, y;
 
 function down() {
 flag = true;
 var touch;
 if(event.touches) {
 touch = event.touches[0];
  } else {
  touch = event;
 }
 cur.x = touch.clientX;
 cur.y = touch.clientY;
 dx = div2.offsetLeft;
 dy = div2.offsetTop;
 }
 
 function move() {
 if(flag) {
  var touch;
  if(event.touches) {
  touch = event.touches[0];
  } else {
  touch = event;
  }
  nx = touch.clientX - cur.x;
  ny = touch.clientY - cur.y;
  x = dx + nx;
  y = dy + ny;
  div2.style.left = x + "px";
  div2.style.top = y + "px";
  //阻止页面的滑动默认事件
  document.addEventListener("touchmove", function() {
  event.preventDefault();
  }, false);
 }
 }
 //鼠标释放时候的函数
 function end() {
 flag = false;
 }
 var div2 = document.getElementById("div2");
 div2.addEventListener("mousedown", function() {
 down();
 }, false);
 div2.addEventListener("touchstart", function() {
 down();
 }, false)
 div2.addEventListener("mousemove", function() {
 move();
 }, false);
 div2.addEventListener("touchmove", function() {
 move();
 }, false)
 document.body.addEventListener("mouseup", function() {
 end();
 }, false);
 div2.addEventListener("touchend", function() {
 end();
}, false);

效果:

js实现适配移动端的拖动效果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com