Skip to content

Instantly share code, notes, and snippets.

@Ai01
Created February 8, 2020 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ai01/57bd6f89a1ad5e90683b17b7dbd5b94c to your computer and use it in GitHub Desktop.
Save Ai01/57bd6f89a1ad5e90683b17b7dbd5b94c to your computer and use it in GitHub Desktop.
拖拽实现2
<div id="ball"></div>
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;
});
#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