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

如何在AnyChart资源甘特图无数据行悬停时获取时间戳

解决AnyChart资源甘特图无数据区域悬停获取时间戳的问题

要实现悬停无数据行区域时获取光标位置的时间戳,你可以通过监听时间轴的鼠标移动事件,将像素坐标转换为时间戳后传递给tooltip使用。具体实现步骤如下:

  • 声明变量存储当前悬停的时间戳:

    let hoveredTimestamp = null;
    
  • 给时间轴添加mousemove事件监听,将鼠标X坐标转换为对应时间戳:

    chart.getTimeline().listen('mousemove', function(e) {
        // 计算鼠标在图表容器内的相对X坐标
        const x = e.domEvent.clientX - chart.container().getBoundingClientRect().left;
        // 将像素坐标转换为时间戳
        hoveredTimestamp = chart.toTime(x);
    });
    
  • 修改tooltip的格式化逻辑,同时兼容有数据和无数据场景:

    var tlTooltip = chart.getTimeline().tooltip();
    tlTooltip.width(300);
    
    tlTooltip.titleFormat(function () {
        // 有数据时用数据的时间,无数据时用监听得到的时间戳
        const timestamp = this.period ? this.period.start : hoveredTimestamp;
        // 将时间戳格式化为可读字符串
        const formattedTime = anychart.format.dateTime(timestamp, 'yyyy-MM-dd HH:mm:ss');
        return `Schedule for ${this.name} | ${formattedTime}`;
    });
    
    tlTooltip.format(function () {
        const timestamp = this.period ? this.period.start : hoveredTimestamp;
        return `Hovered timestamp: ${anychart.format.dateTime(timestamp, 'yyyy-MM-dd HH:mm:ss')}`;
    });
    

关键说明

  • chart.toTime(x)方法可直接将图表内的像素坐标转换为对应时间戳,不受该位置是否有数据的影响。
  • 在tooltip格式化函数中优先使用this.period(有数据场景),无数据时则使用监听事件获取的hoveredTimestamp。
  • 借助anychart.format.dateTime()可将原始时间戳转换为更友好的日期格式。

完整整合后的代码示例:

var treeData = anychart.data.tree(data, "as-tree");
var chart = anychart.ganttResource();
chart.data(treeData);
chart.container("container").draw();
chart.fitAll();

let hoveredTimestamp = null;

// 监听时间轴鼠标移动事件获取时间戳
chart.getTimeline().listen('mousemove', function(e) {
    const x = e.domEvent.clientX - chart.container().getBoundingClientRect().left;
    hoveredTimestamp = chart.toTime(x);
});

var tlTooltip = chart.getTimeline().tooltip();
tlTooltip.width(300);

tlTooltip.titleFormat(function () {
    const timestamp = this.period ? this.period.start : hoveredTimestamp;
    const timeStr = anychart.format.dateTime(timestamp, 'yyyy-MM-dd HH:mm:ss');
    return `Schedule for ${this.name} | ${timeStr}`;
});

tlTooltip.format(function () {
    const timestamp = this.period ? this.period.start : hoveredTimestamp;
    return `Hovered time: ${anychart.format.dateTime(timestamp, 'yyyy-MM-dd HH:mm:ss')}`;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 07:16:01