zenn_waapi_demo08

by 6242ea4

HTML

<p>右下をドラッグすると幅を変えられます</p>
<div class="wrap"></div>

CSS

.wrap {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  box-sizing: border-box;
  width: 600px;
  max-width: 100%;
  padding: 8px;
  border: solid 2px #0003;
  resize: horizontal;
  overflow: hidden;
  border-radius: 16px;
}

.item {
  height: 60px;
  border-radius: 8px;
}

JavaScript

const container = document.querySelector('.wrap');
for (let i = 0; i < 20; i++) {
  const el = document.createElement('div');
  el.className = 'item';
  el.style.width = 40 + (i * 37) % 80 + 'px';
  el.style.background = `hsl(${i * 18} 70% 60%)`;
  container.append(el);
}

// First: 最初の位置を記録しておく
const last = new Map();
const pos = el => ({ x: el.offsetLeft, y: el.offsetTop });
for (const el of container.children) last.set(el, pos(el));

new ResizeObserver(() => {
  for (const el of container.children) {
    const prev = last.get(el);
    // Last: 変化したあとの位置を取得する
    const now = pos(el);
    last.set(el, now);
    if (!prev) continue;

    // Invert: 前の位置との差を求める
    const dx = prev.x - now.x;
    const dy = prev.y - now.y;
    if (!dx && !dy) continue;

    // Play: 差の分だけずらした状態から 0 に戻す
    el.animate(
      [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'translate(0px, 0px)' }],
      { duration: 300, easing: 'cubic-bezier(.42, 0, .35, 1.02)', composite: 'add' }
    );
  }
}).observe(container);