Created
February 8, 2020 09:07
-
-
Save Ai01/be20d752a99ecdadf37dd2c1b738ad55 to your computer and use it in GitHub Desktop.
拖拽放置
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> | |
<div id="door" > | |
</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'); | |
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); | |
} | |
}); |
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; | |
} | |
#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