Created
February 8, 2020 07:44
-
-
Save Ai01/57bd6f89a1ad5e90683b17b7dbd5b94c to your computer and use it in GitHub Desktop.
拖拽实现2
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
<div id="ball"></div> |
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
const ball = document.getElementById('ball'); | |
let startDrag = false; | |
ball.addEventListener('mousedown', () => { | |
startDrag = true; | |
}); | |
document.addEventListener('mousemove', (e) => { | |
if(!startDrag) return; | |
let x = e.pageX - ball.offsetWidth / 2; | |
let y = e.pageY - ball.offsetHeight / 2; | |
ball.style.left = `${x}px`; | |
ball.style.top = `${y}px`; | |
}); | |
ball.addEventListener('mouseup', () => { | |
startDrag = false; | |
}); |
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
#ball{ | |
background: red; | |
width: 40px; | |
height: 40px; | |
border-radius: 50%; | |
cursor: pointer; | |
position: relative; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment