Created
March 16, 2018 08:53
-
-
Save sosnovskyas/37cd34161c33a564f371107c167a446f to your computer and use it in GitHub Desktop.
Пример простого drag'n'drop
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
<html> | |
<head> | |
<style> | |
body { | |
position: relative; | |
} | |
.cube { | |
position: absolute; | |
left: 100px; | |
top: 100px; | |
height: 100px; | |
width: 100px; | |
background-color: #fff99a; | |
} | |
.cube_active { | |
background-color: #e0ffaf; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="cube"></div> | |
<script> | |
const cube = document.querySelector('.cube'); | |
const onMouseMoveHandler = event => { | |
console.log('onMouseMoveHandler', event.x); | |
cube.style.left = `${event.x - 50}px`; | |
cube.style.top = `${event.y - 50}px`; | |
}; | |
const onMouseUpHandler = event => { | |
console.log('onMouseUpHandler'); | |
cube.classList.remove('cube_active'); | |
// снимаем обработчики с body | |
// !!! именно так, потому что именно в переменной хранится именно эта функция. отписаться | |
// просто от какой то функции нельзя. JS должен знать какой именно обработчик снимать, а | |
// в переменной хранится контекст именно этой функции | |
window.removeEventListener('mouseup', onMouseUpHandler); | |
document.body.removeEventListener('mousemove', onMouseMoveHandler); | |
}; | |
const onMouseDownHandler = event => { | |
const target = event.target.closest('.cube'); | |
if (target) { | |
console.log('onMouseUpHandler'); | |
target.classList.add('onMouseDownHandler'); | |
// добавляем именно на window, чтобы слышать все события даже за пределами | |
window.addEventListener('mouseup', onMouseUpHandler); | |
// добавляем именно на body, чтобы перемещать именно по странице а не по всей вселенной | |
document.body.addEventListener('mousemove', onMouseMoveHandler); | |
} | |
}; | |
// этот хэндлер висит постоянно, его снимать не надо, поскольку куб всегда ждёт клика по нему | |
cube.addEventListener('mousedown', onMouseDownHandler); | |
console.log('qwe'); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment