Last active
March 17, 2023 20:41
-
-
Save Polkovn1k/13e96dac5e306ba7f136d1b6d176e542 to your computer and use it in GitHub Desktop.
Drag to scroll (HTML + CSS +JS)
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
<section> | |
<div class="container"> | |
<div class="item"></div> | |
<div class="item"></div> | |
<div class="item"></div> | |
<div class="item"></div> | |
<div class="item"></div> | |
<div class="item"></div> | |
<div class="item"></div> | |
</div> | |
</section> | |
<style> | |
section { | |
width: 800px; | |
margin: 100px auto 100px auto; | |
} | |
.container { | |
display: flex; | |
align-items: center; | |
min-height: 100px; | |
overflow-x: auto; | |
/* Курсор тут желательно указать */ | |
cursor: grab; | |
} | |
.container.in-action { | |
/* Эти стили обязательны, т.к. используются в JS */ | |
cursor: grabbing; | |
user-select: none; | |
} | |
.item { | |
flex-shrink: 0; | |
min-height: 80px; | |
width: 200px; | |
margin-right: 5px; | |
background: linear-gradient(135deg,#2aa34f,#2e9577 33%,#6c6dbe 66%,#a979c3); | |
} | |
</style> | |
<script> | |
let options = { | |
//options.elem обязательно - тут указываем DOM который надо скролить | |
elem: document.querySelector('.container'), | |
left: 0, | |
x: 0, | |
}; | |
const addListeners = () => { | |
document.addEventListener('mousemove', mouseMoveHandler); | |
document.addEventListener('mouseup', mouseUpHandler); | |
}; | |
const removeListeners = () => { | |
document.removeEventListener('mousemove', mouseMoveHandler); | |
document.removeEventListener('mouseup', mouseUpHandler); | |
}; | |
const mouseDownHandler = function (evt) { | |
options.elem.classList.toggle('in-action'); | |
options.left = options.elem.scrollLeft; | |
options.x = evt.clientX; | |
addListeners(); | |
}; | |
const mouseMoveHandler = function (evt) { | |
options.elem.scrollLeft = options.left - (evt.clientX - options.x); | |
}; | |
const mouseUpHandler = function () { | |
options.elem.classList.toggle('in-action'); | |
removeListeners(); | |
}; | |
options.elem.addEventListener('mousedown', mouseDownHandler); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment