纯js无组件 实现拖拽兼容pc端和手机端
pc端拖动时候用到的三个事件:mousedown、mousemove、mouseup
在移动端与之相对应的分别是:touchstart、touchmove、touchend事件。
还有一点要注意的是在PC端获取当前鼠标的坐标是:event.clientX和event.clientY,
在移动端获取坐标位置则是:event.touches[0].clientX和event.touches[0].clientY
//判断当前是touch还是click
var touch;
if(event.touches) {touch = event.touches[0];
} else {
touch = event;
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8">
<title>适配移动端和pc端的拖动效果</title>
<style>
#div2 {
position: relative;
top: 0;
left: 0;
width: 100px;
height: 100px;
background: #bbbbbb;
touch-action: none;
}
</style>
</head>
<body>
<div id="div2"></div>
<script>
//是否拖动
var flag = false;
//
var cur = {
x: 0,
y: 0
}
var nx, ny, dx, dy, x, y;
function down() {
flag = true;
var touch;
if(event.touches) {
touch = event.touches[0];
} else {
touch = event;
}
cur.x = touch.clientX;
cur.y = touch.clientY;
dx = div2.offsetLeft;
dy = div2.offsetTop;
}
function move() {
if(flag) {
var touch;
if(event.touches) {
touch = event.touches[0];
} else {
touch = event;
}
nx = touch.clientX - cur.x;
ny = touch.clientY - cur.y;
x = dx + nx;
y = dy + ny;
div2.style.left = x + "px";
div2.style.top = y + "px";
//阻止页面的滑动默认事件
document.addEventListener("touchmove", function() {
event.preventDefault();
}, false);
}
}
//鼠标释放时候的函数
function end() {
flag = false;
}
var div2 = document.getElementById("div2");
div2.addEventListener("mousedown", function() {
down();
}, false);
div2.addEventListener("touchstart", function() {
down();
}, false)
div2.addEventListener("mousemove", function() {
move();
}, false);
div2.addEventListener("touchmove", function() {
move();
}, false)
document.body.addEventListener("mouseup", function() {
end();
}, false);
div2.addEventListener("touchend", function() {
end();
}, false);
</script>
</body>
</html>