パーツ番号 08-15-08 ・ JavaScript使用
ぷるんと震えるゼリードラッグ
ドラッグ中は動きに合わせて伸び縮みし、離すとゼリーのようにぷるんと震えて静止します。WordPressの遊び心あるボタンやマスコットUIに使えます。
プレビュー
ソースコード
HTML
<div class="d08-15-08-jelly" id="d08-15-08-jelly">Drag</div>CSS
.d08-15-08{width:100%;display:flex;align-items:center;justify-content:center}
.d08-15-08-jelly{width:92px;height:92px;border-radius:50%;background:linear-gradient(135deg,#22c55e,#4ade80);color:#fff;font-size:12px;font-weight:800;display:flex;align-items:center;justify-content:center;box-shadow:0 8px 18px rgba(34,197,94,.35);cursor:grab;touch-action:none}
.d08-15-08-jelly.is-drag{cursor:grabbing}
.d08-15-08-jelly.is-wobble{animation:d08-15-08-wobble .6s cubic-bezier(.34,1.56,.64,1)}
@keyframes d08-15-08-wobble{
0%{border-radius:50%}
20%{border-radius:60% 40% 55% 45%/45% 55% 40% 60%}
40%{border-radius:40% 60% 45% 55%/55% 45% 60% 40%}
60%{border-radius:55% 45% 50% 50%/50% 50% 55% 45%}
80%{border-radius:48% 52% 50% 50%/50% 50% 48% 52%}
100%{border-radius:50%}
}JavaScript
(function(){
var root=document.getElementById('item-08-15-08');if(!root)return;
var jelly=root.querySelector('#d08-15-08-jelly');if(!jelly)return;
var dragging=false,sx=0,sy=0,px=0,py=0,lastX=0,lastY=0,raf=null;
function apply(x,y,sxr,syr){jelly.style.transform='translate('+x+'px,'+y+'px) scale('+sxr+','+syr+')';}
jelly.addEventListener('pointerdown',function(e){
dragging=true;jelly.classList.remove('is-wobble');jelly.classList.add('is-drag');
if(raf)cancelAnimationFrame(raf);
sx=e.clientX-px;sy=e.clientY-py;lastX=e.clientX;lastY=e.clientY;
try{jelly.setPointerCapture(e.pointerId);}catch(err){}
});
jelly.addEventListener('pointermove',function(e){
if(!dragging)return;
px=e.clientX-sx;py=e.clientY-sy;
var vx=e.clientX-lastX,vy=e.clientY-lastY;
lastX=e.clientX;lastY=e.clientY;
var stretch=Math.max(-.18,Math.min(.18,vx*.03));
apply(px,py,1+stretch,1-stretch);
});
function end(){
if(!dragging)return;
dragging=false;jelly.classList.remove('is-drag');
var x=px,y=py,vx=0,vy=0,stiff=.16,damp=.72;
function step(){
var fx=(0-x)*stiff,fy=(0-y)*stiff;
vx=(vx+fx)*damp;vy=(vy+fy)*damp;
x+=vx;y+=vy;apply(x,y,1,1);
if(Math.abs(x)>.5||Math.abs(y)>.5||Math.abs(vx)>.5||Math.abs(vy)>.5){
raf=requestAnimationFrame(step);
}else{
px=0;py=0;apply(0,0,1,1);
jelly.classList.add('is-wobble');
setTimeout(function(){jelly.classList.remove('is-wobble');},650);
}
}
raf=requestAnimationFrame(step);
}
jelly.addEventListener('pointerup',end);
jelly.addEventListener('pointercancel',end);
})();クラス名 .d08-15-08 は本ライブラリ内での識別用です。複数のパーツを同じページで使う場合は、重複しないよう名前を変更してください。