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

Fullcalendar拖拽时获取坐标:实现拖拽事件切换月份功能

FullCalendar拖拽事件时实时获取位置并切换月份的实现方法

核心思路

不用纠结官方是否提供拖拽进行中的回调,直接通过监听全局的鼠标/触摸移动事件,结合拖拽开始时标记的事件元素,就能实时追踪拖拽位置,再对比日历容器的边界来触发月份切换。

具体实现步骤

  • 步骤1:标记拖拽状态并绑定实时监听
    在拖拽开始的回调里,记录当前拖拽的事件元素,同时给document绑定鼠标和触摸移动事件,用来实时捕捉位置变化。示例代码:

    let draggingEventEl = null;
    let calendarInstance = null; // 提前初始化你的FullCalendar实例
    
    document.addEventListener('DOMContentLoaded', function() {
      calendarInstance = new FullCalendar.Calendar(document.getElementById('calendar'), {
        // 你的日历基础配置
        eventDragStart: function(info) {
          draggingEventEl = info.el;
          // 绑定实时移动监听
          document.addEventListener('mousemove', handleDragMove);
          document.addEventListener('touchmove', handleDragMove, { passive: false });
        },
        eventDragStop: function() {
          // 拖拽结束后清理状态、移除监听
          draggingEventEl = null;
          document.removeEventListener('mousemove', handleDragMove);
          document.removeEventListener('touchmove', handleDragMove);
        }
      });
      calendarInstance.render();
    });
    
  • 步骤2:实现位置检测与月份切换逻辑
    在自定义的移动监听函数里,获取拖拽元素和日历容器的位置信息,判断是否超出边界,触发月份切换:

    function handleDragMove(e) {
      if (!draggingEventEl || !calendarInstance) return;
      
      const calendarEl = calendarInstance.el;
      const calendarRect = calendarEl.getBoundingClientRect();
      // 取拖拽元素的中心位置作为判断基准(也可以换成左/右边缘,按需调整)
      const dragElRect = draggingEventEl.getBoundingClientRect();
      const dragCenterX = dragElRect.left + dragElRect.width / 2;
    
      // 超出左边界,切换上月
      if (dragCenterX < calendarRect.left - 20) { // 20是缓冲值,避免误触
        calendarInstance.prev();
        // 短暂取消监听,防止连续快速切换
        setTimeout(() => {
          document.addEventListener('mousemove', handleDragMove);
          document.addEventListener('touchmove', handleDragMove, { passive: false });
        }, 500);
        document.removeEventListener('mousemove', handleDragMove);
        document.removeEventListener('touchmove', handleDragMove);
      }
      // 超出右边界,切换下月
      else if (dragCenterX > calendarRect.right + 20) {
        calendarInstance.next();
        setTimeout(() => {
          document.addEventListener('mousemove', handleDragMove);
          document.addEventListener('touchmove', handleDragMove, { passive: false });
        }, 500);
        document.removeEventListener('mousemove', handleDragMove);
        document.removeEventListener('touchmove', handleDragMove);
      }
    }
    

注意事项

  • 设置缓冲值(示例中的20)是为了避免鼠标刚碰到边界就触发切换,提升用户体验。
  • 切换月份后短暂移除监听再重新绑定,防止连续快速切换导致的异常。
  • 移动端要注意touchmove的passive配置,避免和页面滚动冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:10:17