ドラッグ&ドロップ操作中に画面端へ移動した際、dnd-kit ではスクロール制御のための仕組みとして autoScroll が用意されている
ただ、このデフォルトの設定ではスクロール速度の調整ができないのでカスタマイズしたく調べた
DndContext | @dnd-kit – Documentation
autoScroll の基本
DndContext に autoScroll プロパティを指定することで、ドラッグ中に自動スクロールが有効になる
使用例
<DndContext autoScroll={true} onDragEnd={handleDragEnd}> ... </DndContext>
特徴
- 画面端やスクロール可能な要素の端に近づくと自動でスクロールする
- 対応するのは、window もしくは overflow が設定された要素
- デフォルトでは autoScroll は有効(true)
課題
- スクロール速度の調整ができない
- 特定のスクロールコンテナ内だけで制御したい場合に柔軟性が足りない
- タッチデバイスで挙動が不安定になることがある
手動スクロールの実装
onDragMove イベントを利用して、ポインタの位置に応じてスクロールを制御する
実装例
const handleDragMove = (event) => { const threshold = 50; const scrollSpeed = 10; const container = document.querySelector('.scroll-container'); const pointerY = event.activatorEvent.clientY; const rect = container.getBoundingClientRect(); if (pointerY < rect.top + threshold) { container.scrollTop -= scrollSpeed; } else if (pointerY > rect.bottom - threshold) { container.scrollTop += scrollSpeed; } };
<DndContext autoScroll={false} onDragMove={handleDragMove}> <div className="scroll-container"> ... </div> </DndContext>