Last active
September 17, 2018 08:31
-
-
Save ssdemajia/6dd69e82b3d4a0332ec8d49cf5a1e79b to your computer and use it in GitHub Desktop.
js实现拖拽功能
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"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Document</title> | |
</head> | |
<body> | |
<div id="drag"> | |
wa | |
</div> | |
</body> | |
<script> | |
let isDrag = false; | |
let startX, startY; | |
let drag = document.querySelector('#drag'); | |
drag.addEventListener('mousedown', function(e) { | |
console.log('mouse down',e); | |
startX = e.offsetX; // offsetX表示点击时,鼠标相对于div的位置,div的左上角为坐标(0,0) | |
startY = e.offsetY; | |
isDrag = true; | |
}) | |
drag.addEventListener('mouseup', function(e) { | |
console.log('mouse up',e); | |
isDrag = false; | |
}) | |
drag.addEventListener('mousemove', function(e) { | |
if (isDrag === true) { | |
let xx = e.pageX - startX; // pageX 表示当前移动事件的鼠标在整个文档中的X轴位置,减去之前偏移后得到新的div在文档中的位置。 | |
let yy = e.pageY - startY; // pageY 表示当前移动事件的鼠标在整个文档中的Y轴位置 | |
drag.style.left = xx+ 'px'; | |
drag.style.top = yy + 'px'; | |
} | |
}) | |
</script> | |
<style> | |
#drag { | |
background-color: aquamarine; | |
position: absolute; | |
width: 100px; | |
height: 100px; | |
} | |
</style> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment