You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在父容器约束下让调整尺寸的Div自动换行(仿FullCalendar)

实现类似FullCalendar的Div调整后自动换行效果(基于InteractJS)

嘿,我来帮你搞定这个需求!要让受父容器(比如.month)约束的Div在调整宽度后自动跳转到下一行,核心思路是实时监测Div的右边界是否超出父容器范围,一旦溢出就触发换行逻辑——调整Div的位置到下一行,并重置宽度适配剩余空间。下面是具体的实现方案:

核心思路拆解

  • 实时计算当前Div的总占用宽度(偏移量x + 调整后的宽度)
  • 对比父容器.month的可用宽度,判断是否溢出
  • 溢出时,将Div的垂直偏移y增加一行高度,水平偏移x重置为0,同时把宽度调整为父容器的满宽(或按需调整)
  • 后续继续支持调整新位置上的Div宽度

修改后的完整代码

// 假设resizeDiv是目标调整元素,.month是父容器
const parentContainer = document.querySelector('.month');
const rowHeight = 30; // 定义每行高度,需与你的实际布局匹配

interact(resizeDiv)
  .resizable({
    edges: { left: true, right: true, bottom: false, top: false },
    restrictEdges: { endOnly: true, outer: '.month' },
    restrictSize: { min: { width: 80, height: rowHeight }, max: { height: rowHeight } },
    inertia: true,
  })
  .on('resizemove', function (event) {
    const target = event.target;
    let x = parseFloat(target.getAttribute('data-x')) || 0;
    let y = parseFloat(target.getAttribute('data-y')) || 0;
    const parentWidth = parentContainer.offsetWidth;
    const newWidth = event.rect.width;
    const currentRightEdge = x + newWidth;

    // 关键逻辑:判断是否超出父容器,触发换行
    if (currentRightEdge > parentWidth) {
      // 跳转到下一行:垂直偏移增加行高,水平偏移重置为0
      y += rowHeight;
      x = 0;
      // 换行后默认设为父容器满宽,也可改为最小宽度让用户继续调整
      target.style.width = parentWidth + 'px';
    } else {
      // 未溢出时正常更新宽度
      target.style.width = newWidth + 'px';
    }

    // 更新元素位置与样式
    target.style.height = event.rect.height + 'px';
    target.style.transform = `translate(${x}px, ${y}px)`;
    target.setAttribute('data-x', x);
    target.setAttribute('data-y', y);
    target.textContent = `${Math.round(newWidth)}×${Math.round(event.rect.height)}`;
  });

关键细节说明

  1. 父容器宽度获取:用parentContainer.offsetWidth拿到.month的实际可用宽度,确保溢出判断的准确性
  2. 换行触发条件:当x + 新宽度超过父容器宽度时,立即触发换行逻辑
  3. 行高匹配:rowHeight必须和你布局中每行的高度一致,才能保证跳转位置准确
  4. 宽度重置:换行后默认设为父容器满宽,你也可以改成最小宽度,保留用户后续调整的空间

效果参考(类似FullCalendar)

FullCalendar调整换行示例

内容的提问来源于stack exchange,提问作者Neo_0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:13:14