<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<title></title>
</head>
<style>
html,body{
width:100%;
height:100%;
overflow: hidden;
}
html ,
body,
div{
padding:0;
margin:0;
}
#drag{
width:100px;
height:100px;
background:pink;
-webkit-transform:translate3d(0px,0px,0px);
}
</style>
<body>
<div id="drag"></div>
<script>
function dragMove( obj ){
var oDrag = document.querySelector( obj ) ;
//开始
var dragStart = function( event ){
//阻止冒泡行为
event.stopPropagation();
//把当前获取的位置进行处理
var nowLocation = window.getComputedStyle(oDrag , null)['-webkit-transform'].replace(/[a-z()]/g , '');
var nowLocationArr = nowLocation.split(',');
//起始值 减去 位置值 等于 当前值
this.startX = event.touches[0].pageX - nowLocationArr[4];
this.startY = event.touches[0].pageY - nowLocationArr[5];
}
//移动
var dragMove = function( event ){
//阻止冒泡及默认行为
event.stopPropagation();
event.preventDefault();
if ( event.targetTouches.length == 1 ) {
//移动的 x 和 y 值
this.offsetX = event.targetTouches[0].pageX - this.startX;
this.offsetY = event.targetTouches[0].pageY - this.startY;
//DIV 块活动区域
var clientX = document.body.clientWidth - window.getComputedStyle( this , null )['width'].replace('px','');
var clientY = document.body.clientHeight - window.getComputedStyle( this , null )['height'].replace('px','');
if ( this.offsetX < 0 ) {
this.offsetX = 0;
}else if ( this.offsetX > clientX ) {
this.offsetX = clientX;
}
if ( this.offsetY < 0 ) {
this.offsetY = 0;
}else if ( this.offsetY > clientY ) {
this.offsetY = clientY;
}
this.style['-webkit-transform'] = 'translate3d( '+ this.offsetX +'px , '+ this.offsetY +'px , 0px)';
}
}
//监听事件
oDrag.addEventListener('touchstart' , dragStart );
oDrag.addEventListener('touchmove' , dragMove);
}
//调用
dragMove('#drag');
</script>
</body>
</html>