编辑:
在 miro 指出了我更新情节的一个缺陷之后,我回去重写了这个例子。现在我的十字准线在数据刷新后保持活动状态,这与以前不同,但我图例中的“y”值根本无法更新。在这个更新的代码中需要做什么来使“y”值反映十字准线的当前位置?
jsfiddle:http: //jsfiddle.net/U9ryR/2/
<html>
<head>
<script type="text/javascript">
var highPoint=0;
var highCount=0;
$(function() {
function getPoints() {
var dataPoints = [];
for (var i=0; i<=100; i++) {
if (i == highPoint && highCount < 20) {
dataPoints[i]=[i,8];
highCount++;
} else {
var randomnumber=Math.floor(Math.random()*2);
dataPoints[i]=[i,randomnumber];
}
if (highCount == 20) { highCount = 0; }
}
if (highPoint == 100) { highPoint=0; }
if (highCount == 19) { highPoint++; }
return dataPoints;
}
var plot = $.plot("#placeholder",
[{ data: getPoints(highPoint,highCount),
label: "y = 0"}], {
series: {
lines: { show: true }
},
crosshair: { mode: "x" },
grid: { hoverable: true, autoHighlight: false },
yaxis: { min: 0, max: 10 }
});
var legends = $("#placeholder .legendLabel");
legends.each(function () {
$(this).css('width', $(this).width());
});
var updateLegendTimeout = null;
var latestPosition = null;
function updateLegend() {
updateLegendTimeout = null;
var pos = latestPosition;
var axes = plot.getAxes();
if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max ||
pos.y < axes.yaxis.min || pos.y > axes.yaxis.max)
return;
var i, j, dataset = plot.getData();
for (i = 0; i < dataset.length; ++i) {
var series = dataset[i];
// find the nearest points, x-wise
for (j = 0; j < series.data.length; ++j)
if (series.data[j][0] > pos.x)
break;
// now interpolate
var y, p1 = series.data[j - 1], p2 = series.data[j];
if (p1 == null)
y = p2[1];
else if (p2 == null)
y = p1[1];
else
y = p1[1] + (p2[1] - p1[1]) * (pos.x - p1[0]) / (p2[0] - p1[0]);
legends.eq(i).text(series.label.replace(/=.*/, "= " + y.toFixed(2)));
}
}
function update() {
$("h1").text(highPoint);
$("h2").text(highCount);
plot.setData([getPoints()]);
plot.draw();
$("#placeholder").bind("plothover", function (event, pos, item) {
latestPosition = pos;
if (!updateLegendTimeout)
updateLegendTimeout = setTimeout(updateLegend, 50);
});
setTimeout(update, 100);
}
update();
});
</script>
</head>
<body>
<h1></h1>
<h2></h2>
<div id="placeholder" style="width:500px;height:300px;"></div>
</body>
</html>