簡體   English   中英

如何在 CSS 和 JS 中創建可滾動/可觸摸的網格?

[英]How to create a scrollable/touchable grid in CSS and JS?

我對如何制作一個包含不確定數量的列和行的網格感興趣,我可以將它們放在另一個 div 中,並且不會溢出到其他對象或弄亂父大小。

我希望它是方形的,我正在使用 Tailwind CSS,但我可以適應 SCSS 或 vanilla CSS。 此外,我希望它可以通過桌面上的鼠標和具有觸摸功能的設備進行觸摸/移動。

我將如何實現這一目標?

假設我正確理解了您的問題,這是您可以做到的一種方法。 我沒有用觸摸設備測試過它,但修改它以響應觸摸事件應該不難。

 const items = [ ['a0', 'a1', 'a2'], ['b0', 'b1', 'b2'], ['c0', 'c1', 'c2'] ]; let html = ''; for (let rowItems of items) { html += '<div class="row">'; for (let item of rowItems) { html += '<div class="item">'; html += item; html += '</div>'; } html += '</div>'; } const viewElem = document.querySelector('#view'); const outputElem = document.querySelector('#output'); outputElem.innerHTML = html; let mouseStartPos = null; let startOffset = null; outputElem.addEventListener('mousedown', e => { outputElem.classList.remove('animate'); mouseStartPos = { x: e.clientX, y: e.clientY }; startOffset = { x: outputElem.offsetLeft - viewElem.offsetLeft, y: outputElem.offsetTop - viewElem.offsetTop }; }); window.addEventListener('mouseup', e => { mouseStartPos = null; startOffset = null; outputElem.classList.add('animate'); const xGridOffset = -1 * Math.max(0, Math.min(Math.round((outputElem.offsetLeft - viewElem.offsetLeft) / -100), items.length - 1)); const yGridOffset = -1 * Math.max(0, Math.min(Math.round((outputElem.offsetTop - viewElem.offsetTop) / -100), items[0].length - 1)); outputElem.style.left = `${xGridOffset * 100}px`; outputElem.style.top = `${yGridOffset * 100}px`; }); window.addEventListener('mousemove', e => { if (mouseStartPos) { const xOffset = mouseStartPos.x - e.clientX; const yOffset = mouseStartPos.y - e.clientY; outputElem.style.left = `${-1 * xOffset + startOffset.x}px`; outputElem.style.top = `${-1 * yOffset + startOffset.y}px`; } });
 #view { width: 100px; height: 100px; overflow: hidden; border: 2px solid blue; } #output { position: relative; } .row { display: flex; } .item { display: flex; min-width: 100px; width: 100px; height: 100px; box-sizing: border-box; justify-content: center; align-items: center; border: 1px solid red; } #output.animate { transition: left 1s ease 0s, top 1s ease 0s; }
 Drag it!<br/> <br/> <div id="view"> <div id="output"></div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM