Jquery拖拽元素方法

//初始化div拖拽 参数分别为:元素,拖拽方向(L和R代表靠左或右拖拽,为空或null表示随意拖拽),minLeft,maxLeft表示距两边距离,mtop距顶端距离,mBottom距离底边距离
function initDivMove(deeplinkdiv,direction,minLeft,maxLeft,mTop,oBottom) {
var moves = ["touchstart", "touchmove", "touchend"]
var isdown = false;
var flag = "touch";
var maxH = document.body.clientHeight;
var oL;
var oR;
var oT;
//移动开始
deeplinkdiv.addEventListener(moves[0], function (e) {
isdown = true;
var ev = e || window.event;
var touch = flag == "touch" ? ev.targetTouches[0] : ev;
if (direction == "L") {
oL = 0;
} else if (direction == "R") {
oR = 0;
} else {
oL = touch.clientX - deeplinkdiv.offsetLeft;
}
oT = touch.clientY - deeplinkdiv.offsetTop;
deeplinkdiv.addEventListener(moves[1], preventDefault, false);

});
//移动中
deeplinkdiv.addEventListener(moves[1], function (e) {
if (!isdown) { return; }
var ev = e || window.event;
var touch = flag == "touch" ? ev.targetTouches[0] : ev;
var oLeft = oL;
var oRight = oR;
var oTop = touch.clientY - oT;
if (oTop < mTop) {
oTop = mTop;
} else if (oTop >= maxH - oBottom) {
oTop = maxH - oBottom;
}
if (direction == "L") {
deeplinkdiv.style.left = oLeft + 'px';
} else if (direction == "R") {
deeplinkdiv.style.Right = oRight + 'px';
} else {

oLeft = touch.clientX - oLeft;
if (oLeft < minLeft) { oLeft = minLeft }
if (oLeft > maxLeft) { oLeft = maxLeft }
deeplinkdiv.style.left = oLeft + 'px';
}

deeplinkdiv.style.top = oTop + 'px';

});
//触摸结束
deeplinkdiv.addEventListener(moves[2], function () {
isdown = false;
document.removeEventListener(moves[1], preventDefault);
});

}

posted @ 2021-03-16 17:49  喵~喵  阅读(772)  评论(0编辑  收藏  举报