2
後米羅指出了我是如何更新我回去,並改寫了示例中的情節漏洞。現在我的十字線在數據刷新之後保持活躍,與之前不同,這很好,但是我的傳奇中的「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>
好的,所以我做了你所說的,我現在有十字準線保留,但我仍然有問題保留十字線的最後y值。這是我更新的jsfiddle:http://jsfiddle.net/U9ryR/1/ – 2013-05-10 15:39:57
用新代碼更新了原始問題:http://jsfiddle.net/U9ryR/2/ – 2013-05-10 17:44:32
變量作用域有問題。的console.log(series.label); (把它放在.replace之前.replace)它返回undefined ... idk – Miro 2013-05-10 17:58:44