transfrom 小球拖拽


<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
/>
<style>
body {
height: 2000px;
margin: 0;
}

#block {
width: 100px;
height: 100px;
background-color: red;
border-radius: 100%;
}
</style>
</head>

<body>
<div id="block"></div>
<script>
// 获取节点
var oDiv = document.getElementById("block");
var oW, oH, oLeft, oTop, endLeft, endTop;
// 绑定touchstart事件
oDiv.addEventListener("touchstart", start , false)
oDiv.addEventListener("touchmove", move, false);
oDiv.addEventListener("touchend", end, false);
function start(e) {
e.preventDefault();
e.stopPropagation();
var touches = e.touches[0];
oW = touches.clientX ;
oH = touches.clientY
}
function move(e) {
e.preventDefault();
e.stopPropagation();
var touches = e.touches[0];
if (endLeft || endTop) {
oLeft = endLeft + touches.clientX - oW;
oTop = endTop + touches.clientY - oH;
} else {
oLeft = touches.clientX - oW;
oTop = touches.clientY - oH;
}
if (oLeft <= 0) {
oLeft = 0;
} else if (oLeft > window.innerWidth - oDiv.offsetWidth) {
oLeft = (window.innerWidth - oDiv.offsetWidth);
}
if(oTop <= 0) {
oTop = 0;
} else if (oTop > window.innerHeight - oDiv.offsetHeight) {
oTop = (window.innerHeight - oDiv.offsetHeight);
}
oDiv.style.transform = "translate(" + oLeft + "px," + oTop + "px)"
}
function end(e) {
e.preventDefault();
e.stopPropagation();
var touches = e.touches[0];
endLeft = oLeft;
endTop = oTop;
}
</script>
</body>

</html>
 
 
 
posted @ 2017-09-21 09:53  玛丽莲梦露  阅读(247)  评论(0编辑  收藏  举报