我正在尝试实现将跟随鼠标光标的图例。它有效,但是有一个问题:图例div绘制在图的下方,这不是我想要的。
请参阅以下MWE:
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<script src="static/dygraph.min.js"></script>
<link rel="stylesheet" href="static/dygraph.css" />
<style>
#graph {
height: 400px;
width: 640px;
}
#legend {
position: absolute;
background-color: red;
/* z-index: 99; */
}
</style>
</head>
<body>
<div id="legend"></div>
<div id="graph"></div>
<script>
document.onmousemove = function(e) {
var legend = document.getElementById("legend");
legend.style.left = e.pageX + "px";
legend.style.top = e.pageY + "px";
};
var data = [];
for(let i = 0; i < 100; i++) {
data.push([i, Math.random(), Math.random()]);
}
var g = new Dygraph(
"graph",
data,
{
fillGraph: true,
fillAlpha: 0.8,
labels: ["x", "y1", "y2"],
labelsDiv: legend,
legendFormatter: legendFormatter
}
);
function legendFormatter(data) {
if(data.x === null) return "";
return data.xHTML + "<br />" +
data.series.map(
v => "<span style='color:" + v.color + ";'>" +
v.labelHTML + "</span>: " + v.yHTML
).join("<br />");
}
</script>
</body>
</html>
以下屏幕截图显示了当前行为(这不是我想要的):
我的本能是将图例设置为具有较高的z索引。但是,这样做会导致一些奇怪的行为。
在Firefox中,图例只是消失了。
在Chromium中,当光标静止(在图形上)时,图例不可见,并且在光标移动时可以看到图例闪烁。
这是为什么,如何使图例正确显示(在图形顶部)?
当光标离开图形时,我仍然希望隐藏图例,因此不能设置#legend { display: block !important; }
。
答案 0 :(得分:1)
1):图例div在顶部,并移动到光标的位置,
这会混淆突出显示正在悬停的数据点的图形函数。
您会注意到图例div消失时,图形上的任何点都不会突出显示。
这会导致闪烁...
要解决此问题,请在x,y位置添加一些像素,
因此图例div不在光标正下方。
legend.style.left = (e.pageX + 16) + "px";
legend.style.top = (e.pageY + 16) + "px";
加上,鼠标将隐藏部分信息,否则...
2),将图例div放置在图形顶部,而无需添加z-index,
在图div之后,在dom的后面添加图例div ...
<div id="graph"></div>
<div id="legend"></div>
3)参见以下工作片段...
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.css" />
<style>
#graph {
height: 400px;
width: 640px;
}
#legend {
position: absolute;
background-color: red;
}
</style>
</head>
<body>
<div id="graph"></div>
<div id="legend"></div>
<script>
var legend = document.getElementById("legend");
document.onmousemove = function(e) {
legend.style.left = (e.pageX + 16) + "px";
legend.style.top = (e.pageY + 16) + "px";
};
var data = [];
for(let i = 0; i < 100; i++) {
data.push([i, Math.random(), Math.random()]);
}
var g = new Dygraph(
"graph",
data,
{
fillGraph: true,
fillAlpha: 0.8,
labels: ["x", "y1", "y2"],
labelsDiv: legend,
legendFormatter: legendFormatter,
}
);
function legendFormatter(data) {
//if(data.x === null) return "";
return data.xHTML + "<br />" +
data.series.map(
v => "<span style='color:" + v.color + ";'>" +
v.labelHTML + "</span>: " + v.yHTML
).join("<br />");
}
</script>
</body>
</html>