1. 移動端拖動元素移動
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 100px;
height: 100px;
background-color: aqua;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="one two"></div>
<script>
var div = document.querySelector('div');
div.addEventListener('touchstart', function(e) {
var x = e.targetTouches[0].pageX - this.offsetLeft;
var y = e.targetTouches[0].pageY - this.offsetTop;
document.addEventListener('touchmove', move);
function move(e) {
div.style.left = e.targetTouches[0].pageX - x + 'px';
div.style.top = e.targetTouches[0].pageY - y + 'px';
}
document.addEventListener('touchend', function() {
document.removeEventListener('touchmove', move);
})
})
</script>
</body>
</html>
2. pc端拖動元素移動
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 100px;
height: 100px;
background-color: aqua;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="one two"></div>
<script>
var div = document.querySelector('div');
div.addEventListener('mousedown', function(e) {
console.log();
var x = e.pageX - div.offsetLeft;
var y = e.pageY - div.offsetTop;
function move(e) {
div.style.left = e.pageX - x + 'px';
div.style.top = e.pageY - y + 'px';
}
document.addEventListener('mousemove', move);
document.addEventListener('mouseup', function() {
document.removeEventListener('mousemove', move);
})
})
</script>
</body>
</html>