移动端 touch 实现 拖动元素

时间:2024-08-03 14:33:20

var homeMove = (function () {

//touch自适应
var k = "ontouchend" in window ? "touchend" : "click";

var isdrag = false;
var moveid = document.getElementById("moveid");
var sWidth = document.body.clientWidth;
var sHeight = document.documentElement.clientHeight; //window.screen.height;
var width = moveid.offsetWidth;
var height = moveid.offsetHeight;
var tx, x;
var ty, y;
var i = 0, j = 0; ;

function movemousex(e) {

  e.preventDefault();

  if (isdrag) {
    var n = tx + e.touches[0].pageX - x;
    var maxWidth = sWidth - width;
    if (n > maxWidth) {
      n = maxWidth;
    } else if (n < 0) {
      n = 0;
    }
    $('#moveid').css("left", n);
    return false;
  }
}

function selectmousex(e) {

  isdrag = true;
  tx = parseInt(moveid.offsetLeft + 0);
  x = e.touches[0].pageX;
  return false;
}

function movemousey(e) {
  e.preventDefault();
  if (isdrag) {
    var n = ty + e.touches[0].pageY - y;
    var maxHeight = sHeight - height;
    if (n > maxHeight) {
      n = maxHeight;
    } else if (n < 0) {
      n = 0;
    }
    $('#moveid').css("top", n);
    return false;
  }
}

function selectmousey(e) {

  isdrag = true;
  ty = parseInt(moveid.offsetTop + 0);
  y = e.touches[0].pageY;
  return false;
}

function addMoveEvent() {
  moveid.addEventListener('touchend', function () {
    isdrag = false;
  });
  moveid.addEventListener('touchstart', selectmousex);
  moveid.addEventListener('touchmove', movemousex, false);
  moveid.addEventListener('touchstart', selectmousey);
  moveid.addEventListener('touchmove', movemousey, false);
  moveid.onclick = function () {
    window.location.href = "/";
  }
}

return { addMoveEvent: addMoveEvent };

} ());

$(function () {
  homeMove.addMoveEvent();
});