javascript - (Vis.js 网络)getPositions 的节点坐标不正确?
问题描述
在我的vis.js 网络中,当我单击节点时,我想让一个弹出窗口出现在节点的位置。
我使用了getPositions方法,但弹出窗口出现在错误的位置(左上角太多),好像坐标不正确。
network.on("click", function (params) {
// Get the node ID
var nodeId = params.nodes[0];
if (nodeId) {
// Get the node title to show in the popup
var popup = this.body.nodes[nodeId].options.title;
// Get the node coordinates
var nodePosition = network.getPositions(nodeId);
var nodeX = nodePosition[nodeId].x;
var nodeY = nodePosition[nodeId].y;
// Show the tooltip in a div
document.getElementById('popup').innerHTML = popup;
document.getElementById('popup').style.display = "block";
// Place the div
document.getElementById('popup').style.position = "absolute";
document.getElementById('popup').style.top = nodeY+'px';
document.getElementById('popup').style.left = nodeX+'px';
}
});
// Empty and hide the div when click elsewhere
network.on("deselectNode", function (params) {
document.getElementById('popup').innerHTML = null;
document.getElementById('popup').style.display = "none";
});
解决方案
我在github 的 vis 支持部分得到了一些帮助。原来诀窍是使用canvasToDOM()
.
以下是它如何应用于我的代码:
network.on("click", function(params) {
// Get the node ID
var nodeId = params.nodes[0];
if (nodeId) {
// Get the node title to show in the popup
var popup = this.body.nodes[nodeId].options.title;
// Get the node coordinates
var { x: nodeX, y: nodeY } = network.canvasToDOM(
network.getPositions([nodeId])[nodeId]
);
// Show the tooltip in a div
document.getElementById("popup").style.display = "block";
// Place the div
document.getElementById("popup").style.position = "absolute";
document.getElementById("popup").style.top = nodeY + "px";
document.getElementById("popup").style.left = nodeX + "px";
}
});
当网络保持不变时它可以工作,但在我的情况下,我想适应网络并放大点击的节点,所以弹出窗口不会跟随,但由于这是一个单独的问题,我将发布另一个问题。
推荐阅读
- html - 基于 URL 参数,使用 jQuery 设置下拉选项
- excel - 在每个内部循环之后开始一个新的数组列
- java - 无法确定 Android API 21 平台 (/home/user/Android/Sdk) 的“tools.jar”库的路径
- shopify - 无法在shopify中创建产品
- python - 用 Moto 模拟 AWS lambda
- r - R - setwd(tempdir())中的错误:无法更改工作目录
- java - 如何保存生成的 ID 并将其用于删除
- google-apps-script - 用于打印 pdf 和发送电子邮件的 Apps 脚本忽略了 Google Sheet 分页符。如何在原始 Google 表格中保留分页符?
- data-cleaning - 数据框单元格内重复数据的数据清理
- javascript - 如何使固定元素成为条形?