Scroll orizzontale della pagina
Esempio
<div id="board-scroll" class="items"> <div class="item item1"></div> <div class="item item2"></div> <div class="item item3"></div> <div class="item item4"></div> <div class="item item5"></div> <div class="item item6"></div> <div class="item item7"></div> <div class="item item8"></div> <div class="item item9"></div> <div class="item item10"></div> </div>
Script:
// scroll orizzontale scrollHorizontal( '#board-scroll' );
Css:
@supports ( display: grid ) { .items { width: 100%; overflow-x: scroll; overflow-y: hidden; white-space: nowrap; will-change: transform; user-select: none; cursor: pointer; } .item.active { background: rgba(255,255,255,0.3); cursor: grabbing; cursor: -webkit-grabbing; } }
Funzione
/** * Scroll orizzontale tramite drag del mouse * @param string class_id class eo id dell'elemento che contiene gli elementi */ function scrollHorizontal( class_id ) { const slider = document.querySelector( class_id ); let isDown = false; let startX; let scrollLeft; slider.addEventListener('mousedown', (e) => { isDown = true; slider.classList.add('active'); startX = e.pageX - slider.offsetLeft; scrollLeft = slider.scrollLeft; }); slider.addEventListener('mouseleave', () => { isDown = false; slider.classList.remove('active'); }); slider.addEventListener('mouseup', () => { isDown = false; slider.classList.remove('active'); }); slider.addEventListener('mousemove', (e) => { if (!isDown) return; e.preventDefault(); const x = e.pageX - slider.offsetLeft; const walk = (x - startX) * 2; //scroll-fast slider.scrollLeft = scrollLeft - walk; console.log(walk); }); }