天天看點

移動端元素拖拽之touchstart, touchmove,touchend簡易版本

!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
<style>
* {
 margin: 0;
 padding: 0;
}
html,
body {
 width: 100%;
 height: 100%;
}
#div {
 width:30px;
 height: 40px;
 background: red;
 position: absolute;
}</style>
</head>
<body>
    <div id="div"></div>
</body>
<script>
var $div = document.querySelector('#div')
var mw = document.body.clientWidth;
var mh = document.body.clientHeight;
var ow = $div.offsetWidth
var oh = $div.offsetHeight

$div.addEventListener('touchstart', function(e) {
 var e = e || window.event;
 var touch = e.targetTouches[0];
 oL = touch.clientX - $div.offsetLeft;
 oT = touch.clientY - $div.offsetTop;
 document.addEventListener("touchmove", function(e){e.preventDefault}, false);
});
//觸摸中的,位置記錄
$div.addEventListener('touchmove', function(e) {
 var e = e || window.event;
 var touch = e.changedTouches[0];
 var left = touch.clientX - oL;
 var top = touch.clientY - oT;
 if(left < 0) {
 left = 0;
 } else if(left >= mw - ow) {
 left = mw - ow;
 }
 if(top < 0) {
 top = 0;
 } else if(top >= mh - oh) {
 top = mh - oh;
 }
 $div.style.left = left + 'px';
 $div.style.top = top + 'px';
});
$div.addEventListener('touchend', function(e) {
 document.removeEventListener("touchmove",function(e){e.preventDefault});
});
</script>
</html>