Skip to content

Instantly share code, notes, and snippets.

@Ai01
Created February 8, 2020 09:07
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/be20d752a99ecdadf37dd2c1b738ad55 to your computer and use it in GitHub Desktop.
Save Ai01/be20d752a99ecdadf37dd2c1b738ad55 to your computer and use it in GitHub Desktop.
拖拽放置
<div id="ball"></div>
<div id="door" >
</div>
const ball = document.getElementById('ball');
const door = document.getElementById('door');
let startDrag = false;
ball.addEventListener('mousedown', () => {
startDrag = true;
});
const mousemoveCb = (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`;
};
document.addEventListener('mousemove', mousemoveCb);
document.addEventListener('mouseup', (e) => {
startDrag = false;
ball.hide = true;
const elementBelow = document.elementFromPoint(e.clientX, e.clientY);
ball.hide = false;
if(elementBelow === door) {
door.appendChild(ball);
ball.style.left = `0px`;
ball.style.top = `0px`;
ball.style.position = 'static';
document.removeEventListener('mousemove', mousemoveCb);
}
});
#ball{
background: red;
width: 40px;
height: 40px;
border-radius: 50%;
cursor: pointer;
position: relative;
}
#door {
width: 400px;
height: 200px;
border: 1px solid black;
position: relative;
top: 100px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment