Created
June 18, 2020 10:43
-
-
Save yinxianwei/9dc66ff3edbeedd0f4e9bf0ba821180c to your computer and use it in GitHub Desktop.
web drag
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>drag</title> | |
<style> | |
.drag { | |
background-color: red; | |
width: 100px; | |
height: 100px; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="drag" | |
onmousedown="mousedown(event)" | |
onmouseup="mouseup(event)"> | |
</div> | |
<script> | |
let _dragEnabled = false; | |
let x = 0; | |
let y = 0; | |
let tx = 0; | |
let ty = 0; | |
function mousedown(ev) { | |
x -= ev.screenX; | |
y -= ev.screenY; | |
_dragEnabled = true; | |
} | |
function mouseup() { | |
_dragEnabled = false; | |
x = tx; | |
y = ty; | |
} | |
let element = document.querySelectorAll('.drag')[0]; | |
document.addEventListener("mousemove", function(ev) { | |
if (!_dragEnabled) { | |
return; | |
} | |
tx = x + ev.screenX; | |
ty = y + ev.screenY; | |
element.style.transform = 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, ' + tx + ', ' + ty + ', 0, 1)'; | |
element.style['-webkit-transform'] = 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, ' + tx + ', ' + ty + ', 0, 1)'; | |
element.style['-ms-transform'] = 'matrix(1, 0, 0, 1, ' + tx + ', ' + ty + ')' | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment