标签:
经上次的手机端拖拽事件,再次经过完善修改,加入了元素不能拖出屏幕范围功能,并做了一个小的函数接口
ps:经落雨大神指点。
代码如下:
var touchEvent = (function(){ var oDiv = document.getElementsByTagName(‘div‘)[0], //获取可拖动元素 oIpt = document.getElementsByTagName(‘input‘)[0], //记录拖动元素位置 oIpt1 = document.getElementsByTagName(‘input‘)[1]; //记录触点位置 var touchSatrtFunc,touchMoveFunc,getTouchEvent; var _this = this; var opinion = { //所需变量集 oDiv : oDiv, oIpt : oIpt, oIpt1 : oIpt1, startX : "", startY : "", startPositionX : "", startPositionY : "", elemWidth : "", elemHeight : "", byWidth : "", byHeight : "" } //触摸点下事件 touchSatrtFunc = function(e){ e.preventDefault(); //阻止触摸时浏览器的缩放、滚动条滚动等 var touch = e.touches[0]; //获取第一个触点 var x = Number(touch.pageX); //页面触点X坐标 var y = Number(touch.pageY); //页面触点Y坐标 //记录触点初始位置 startX = x; startY = y; //可拖动元素距离页面顶部的距离 startPositionY = oDiv.offsetTop; //可拖动元素距离页面左侧的距离 startPositionX = oDiv.offsetLeft; //可拖动元素的宽度 elemWidth = oDiv.offsetWidth; //可拖动元素的高度 elemHeight = oDiv.offsetHeight; //网页可见区域宽 byWidth = document.documentElement.clientWidth ; //网页可见区域高 byHeight = document.documentElement.clientHeight ; } //触摸点下移动事件 touchMoveFunc = function(e){ e.preventDefault(); //阻止触摸时浏览器的缩放、滚动条滚动等 var touch = e.touches[0]; //获取第一个触点 var x = Number(touch.pageX); //页面触点X坐标 var y = Number(touch.pageY); //页面触点Y坐标 var fnyTop = startPositionY + (y-startY), fnyLeft = startPositionX + (x-startX); oIpt.value = "元素位置:" +startPositionX +":"+startPositionY; oIpt1.value = "触点位置:" +x +":"+y; //判断移动到边缘情况 if(fnyLeft <= 0){ oDiv.style.left = 0; if(fnyTop <= 0){ oDiv.style.top = 0; }else if(fnyTop > 0 && fnyTop < (byHeight - elemHeight) ){ oDiv.style.top = fnyTop + ‘px‘; }else if(fnyTop >= (byHeight - elemHeight) ){ oDiv.style.top = byHeight - elemHeight + ‘px‘; } }else if(fnyLeft >= (byWidth - elemWidth) ){ oDiv.style.left = byWidth - elemWidth + ‘px‘; if(fnyTop <= 0){ oDiv.style.top = 0; }else if(fnyTop > 0 && fnyTop < (byHeight - elemHeight) ){ oDiv.style.top = fnyTop + ‘px‘; }else if(fnyTop >= (byHeight - elemHeight) ){ oDiv.style.top = byHeight - elemHeight + ‘px‘; } }else if(fnyLeft > 0 && fnyLeft < (byWidth - elemWidth) ){ oDiv.style.left = fnyLeft + ‘px‘; if(fnyTop <= 0){ oDiv.style.top = 0; }else if(fnyTop > 0 && fnyTop < (byHeight - elemHeight) ){ oDiv.style.top = fnyTop + ‘px‘; }else if(fnyTop >= (byHeight - elemHeight) ){ oDiv.style.top = byHeight - elemHeight + ‘px‘; } } } var touchs = function(){ oDiv.addEventListener(‘touchstart‘,touchSatrtFunc,false); oDiv.addEventListener(‘touchmove‘,touchMoveFunc,false); } return { getTouch:touchs, touchSatrtFunc : touchSatrtFunc, touchMoveFunc : touchMoveFunc } })();
调用此方法时只需加入 touchEvent.getTouch(); 即可
然而此代码还有局限性,目前需要去原js中修改所需要的拖动的元素
标签:
原文地址:http://www.cnblogs.com/hpuzy0127/p/5099045.html