← 動的パーツギャラリーへ戻る

パーツ番号 08-07-03 ・ JavaScript使用

ドラッグ開閉ドロワー

右端のハンドルをドラッグすると引き出しメニューが横から開閉し、指を離すと開閉状態にスナップします。WordPressのサイドメニューに好適です。

dragjs

プレビュー

ソースコード

HTML

<div class="d08-07-03-stage">
          <div class="d08-07-03-drawer" id="d08-07-03-drawer">
            <div class="d08-07-03-content">📁 メニュー<br>・ホーム<br>・お知らせ<br>・設定</div>
            <div class="d08-07-03-handle" id="d08-07-03-handle">▸</div>
          </div>
        </div>

CSS

.d08-07-03-stage{position:relative;width:100%;height:190px;overflow:hidden;border-radius:12px;background:#eef0f7}
        .d08-07-03-drawer{position:absolute;top:0;left:0;width:170px;height:100%;background:#fff;border-radius:12px;box-shadow:2px 0 14px rgba(0,0,0,.12);transform:translateX(-142px);transition:transform .25s cubic-bezier(.2,.8,.3,1);touch-action:none}
        .d08-07-03-drawer.is-dragging{transition:none}
        .d08-07-03-content{padding:18px 16px;font-size:12.5px;font-weight:600;color:#2a2d3a;line-height:2}
        .d08-07-03-handle{position:absolute;top:50%;right:-26px;transform:translateY(-50%);width:26px;height:44px;background:#6a5cff;color:#fff;display:flex;align-items:center;justify-content:center;border-radius:0 8px 8px 0;cursor:grab;font-size:13px}

JavaScript

(function(){
        var root=document.getElementById('item-08-07-03');if(!root)return;
        var drawer=root.querySelector('#d08-07-03-drawer'),handle=root.querySelector('#d08-07-03-handle');
        if(!drawer||!handle)return;
        var OPEN=0,CLOSED=-142,dragging=false,startX=0,startTx=CLOSED,curTx=CLOSED;
        handle.addEventListener('pointerdown',function(e){
          dragging=true;startX=e.clientX;startTx=curTx;
          drawer.classList.add('is-dragging');
          try{handle.setPointerCapture(e.pointerId);}catch(err){}
        });
        handle.addEventListener('pointermove',function(e){
          if(!dragging)return;
          var dx=e.clientX-startX;
          curTx=Math.min(OPEN,Math.max(CLOSED,startTx+dx));
          drawer.style.transform='translateX('+curTx+'px)';
        });
        function end(){
          if(!dragging)return;
          dragging=false;
          drawer.classList.remove('is-dragging');
          curTx=(curTx>CLOSED/2)?OPEN:CLOSED;
          drawer.style.transform='translateX('+curTx+'px)';
        }
        handle.addEventListener('pointerup',end);
        handle.addEventListener('pointercancel',end);
      })();

クラス名 .d08-07-03 は本ライブラリ内での識別用です。複数のパーツを同じページで使う場合は、重複しないよう名前を変更してください。