如何在Flot图中显示包含数据点数据的弹出窗口?

时间:2009-10-01 08:32:15

标签: javascript jquery flot

我得到了Flot创建的图表。我想要实现的是当用户将鼠标移动到它上面时获取某种信息 - 最好是在某种javascript弹出窗口中显示数据(来自x和y轴)。

这可能是一个微不足道的问题,但我无法弄明白......

现在我的javascript看起来像这样:

<script  id="source" language="javascript" type="text/javascript">
$(function () {
    var data = [[1251756000000, 122.68],[1251842400000, 122.68],[1251928800000, 125.13],[1252015200000, 112.62],[1252101600000, 122.76]]
    $.plot($("#graph_placeholder"), [ data ], { 
        xaxis: { mode: "time", minTickSize: [1, "day"], timeformat : "%y/%m/%d", },
        lines: { show: true },
        points: { show: false },
    } );
});
</script>

最好是在悬停点时获得x: 1251756000000 y: 122.68(x:1251756000000,y:任何)。或者甚至将x值格式化为timeformat 2009/11/14 )中定义的格式。

1 个答案:

答案 0 :(得分:5)

This example显示了如何启用工具提示(如果单击“启用工具提示”复选框)。以下是使用示例代码的起点:

<script  id="source" language="javascript" type="text/javascript">
$(function () {
var data = [[1251756000000, 122.68],[1251842400000, 122.68],[1251928800000, 125.13],[1252015200000, 112.62],[1252101600000, 122.76]]
$.plot($("#graph_placeholder"), [ data ], {
    xaxis: { mode: "time", minTickSize: [1, "day"], timeformat : "%y/%m/%d", },
    lines: { show: true },
    points: { show: true },
    grid: { hoverable: true },
} );
});

var previousPoint = null;
$("#graph_placeholder").bind("plothover", function (event, pos, item) {
if (item) {
    if (previousPoint != item.datapoint) {
        previousPoint = item.datapoint;
        $("#tooltip").remove();
        showTooltip(item.pageX, item.pageY, '(' + item.datapoint[0] + ', ' + item.datapoint[1]+')');
    }
} else {
    $("#tooltip").remove();
    previousPoint = null;
}
});

function showTooltip(x, y, contents) {
    $('<div id="tooltip">' + contents + '</div>').css( {
        position: 'absolute',
        display: 'none',
        top: y + 5,
        left: x + 5,
        border: '1px solid #fdd',
        padding: '2px',
        'background-color': '#fee',
        opacity: 0.80
    }).appendTo("body").fadeIn(200);
}
</script>