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

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

ドラッグカラーグラデーションピッカー

虹色バー上のつまみをドラッグすると上のスウォッチがリアルタイムに色替わりします。WordPressのテーマカラー選択UIに応用できます。

dragjs

プレビュー

ソースコード

HTML

<div class="d08-07-08-wrap">
          <div class="d08-07-08-swatch" id="d08-07-08-swatch" style="background:hsl(108,80%,55%)"></div>
          <div class="d08-07-08-bar" id="d08-07-08-bar">
            <div class="d08-07-08-thumb" id="d08-07-08-thumb" style="left:30%"></div>
          </div>
        </div>

CSS

.d08-07-08-wrap{display:flex;flex-direction:column;align-items:center;gap:14px;width:100%;max-width:220px}
        .d08-07-08-swatch{width:52px;height:52px;border-radius:14px;box-shadow:0 4px 12px rgba(0,0,0,.15);border:3px solid #fff;outline:1px solid #eee}
        .d08-07-08-bar{position:relative;width:100%;height:16px;border-radius:99px;background:linear-gradient(90deg,#ff0000,#ffea00,#22ff00,#00e5ff,#2b5cff,#c400ff,#ff0000);touch-action:none}
        .d08-07-08-thumb{position:absolute;top:50%;width:22px;height:22px;border-radius:50%;background:#fff;border:3px solid #fff;box-shadow:0 0 0 2px rgba(0,0,0,.15),0 3px 8px rgba(0,0,0,.25);transform:translate(-50%,-50%);cursor:grab}

JavaScript

(function(){
        var root=document.getElementById('item-08-07-08');if(!root)return;
        var bar=root.querySelector('#d08-07-08-bar'),thumb=root.querySelector('#d08-07-08-thumb'),swatch=root.querySelector('#d08-07-08-swatch');
        if(!bar||!thumb||!swatch)return;
        var dragging=false;
        function setColor(clientX){
          var r=bar.getBoundingClientRect();
          var pct=Math.min(1,Math.max(0,(clientX-r.left)/r.width));
          var hue=Math.round(pct*360);
          thumb.style.left=(pct*100)+'%';
          swatch.style.background='hsl('+hue+',80%,55%)';
        }
        bar.addEventListener('pointerdown',function(e){dragging=true;setColor(e.clientX);try{bar.setPointerCapture(e.pointerId);}catch(err){}});
        bar.addEventListener('pointermove',function(e){if(dragging)setColor(e.clientX);});
        function stop(){dragging=false;}
        bar.addEventListener('pointerup',stop);
        bar.addEventListener('pointercancel',stop);
      })();

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