javascript实现移动端触屏拖拽功能
本文实例为大家分享了javascript实现移动端触屏拖拽的具体代码,供大家参考,具体内容如下
HTML:
<body>
<div id="div1">
</div>
</body>
CSS:
<style media="screen">
* {
margin: 0;
padding: 0;
}
html,body {
width: 100%;
height:100%;
}
#div1 {
width: 50px;
height: 50px;
background: cyan;
position: absolute;
}
</style>
JS:
<script type="text/javascript">
var div1=document.querySelector('#div1');
var maxW=document.body.clientWidth-div1.offsetWidth;
var maxH=document.body.clientHeight-div1.offsetHeight;
div1.addEventListener('touchstart',function(e){
var ev = e || window.event;
var touch = ev.targetTouches[0];
oL = touch.clientX - div1.offsetLeft;
oT = touch.clientY - div1.offsetTop;
document.addEventListener("touchmove",defaultEvent,false);
})
div1.addEventListener('touchmove',function(e){
var ev = e || window.event;
var touch = ev.targetTouches[0];
var oLeft = touch.clientX - oL;
var oTop = touch.clientY - oT;
if(oLeft<0){
oLeft=0;
}else if (oLeft>=maxW) {
oLeft=maxW;
}
if(oTop<0){
oTop=0;
}else if (oTop>=maxH) {
oTop=maxH;
}
div1.style.left = oLeft + 'px';
div1.style.top = oTop + 'px';
})
div1.addEventListener('touchend',function(){
document.removeEventListener("touchmove",defaultEvent);
})
function defaultEvent(e) {
e.preventDefault();
}
</script>
说明 :
maxW:div1可移动的最大宽度
maxH:div1可移动的最大高度
oL、oT:鼠标所点位置的坐标
效果:
以上是 javascript实现移动端触屏拖拽功能 的全部内容, 来源链接: utcz.com/z/311834.html