<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<title>2.4 单指拖拽--拖拽</title>
<style>
body {
height: 2000px;
}
.backtop {
position: fixed;
right: 20px;
bottom: 20px;
width: 45px;
height: 45px;
line-height: 45px;
text-align: center;
background-color: rgba(0, 0, 0, 0.6);
border-radius: 50%;
color: #fff;
font-size: 30px;
-webkit-tap-highlight-color: transparent;
/*transform: translate3d(x, y, 0);*/
}
</style>
</head>
<body>
<a href="#" id="backtop" class="backtop">↑</a>
<script>
function drag(el, options) {
options.x = typeof options.x !== 'undefined' ? options.x : true;
options.y = typeof options.y !== 'undefined' ? options.y : false;
if (!options.x && !options.y) return;
var curPoint = {
x: 0,
y: 0
};
var startPoint = {};
var isTouchMove = false;
el.addEventListener('touchstart', handleStart, false);
el.addEventListener('touchmove', handleMove, false);
el.addEventListener('touchend', handleEnd, false);
function handleStart(ev) {
var touch = ev.changedTouches[0];
startPoint.x = touch.pageX;
startPoint.y = touch.pageY;
}
function handleMove(ev) {
ev.preventDefault();
isTouchMove = true;
var touch = ev.changedTouches[0];
var diffPoint = {};
var movePoint = {
x: 0,
y: 0
};
diffPoint.x = touch.pageX - startPoint.x;
diffPoint.y = touch.pageY - startPoint.y;
if (options.x) {
movePoint.x = diffPoint.x + curPoint.x;
}
if (options.y) {
movePoint.y = diffPoint.y + curPoint.y;
}
move(el, movePoint.x, movePoint.y);
}
function handleEnd(ev) {
if (!isTouchMove) return;
var touch = ev.changedTouches[0];
curPoint.x += touch.pageX - startPoint.x;
curPoint.y += touch.pageY - startPoint.y;
isTouchMove = false;
}
function move(el, x, y) {
x = x || 0;
y = y || 0;
el.style.transform = 'translate3d(' + x + 'px, ' + y + 'px, 0)';
}
}
</script>
<script>
var backtop = document.getElementById('backtop');
drag(backtop, {
x: true,
y: true
// y: true
});
</script>
</body>
</html>