浏览器中渲染的SVG图像:将元素名称复制到剪贴板中

问题描述 投票:1回答:1

在此网页上:http://viz-js.com/,我们看到了一个从文本文件渲染的图形。

如果将鼠标悬停在图形元素之一上,其标签将显示在弹出窗口中。 (在此示例中为“开始”)

enter image description here

问题:无论如何,是否可以使标签成为可选择的,或者添加一些JavaScript以将弹出窗口的文本复制到剪贴板?

我对此的实现具有很长的节点名称(最多44个字符),我希望能够以某种方式进行复制。

谢谢。

编辑:迄今为止尝试过的操作。

使用Chrome的'检查'选项,我发现SVG中的节点似乎具有'node的类名,因此我尝试了以下JavaScript,但没有效果:

$('.big').hover(function () {
    // will not work, no user action
  $('input').select();
    document.execCommand('copy');
});

$('.big').mousedown(function () {
    //works
  document.execCommand('copy');
});

而且我似乎无法使用任何CSS样式来影响图形的外观。

javascript svg graphviz
1个回答
0
投票

[查看SVG,您可以看到悬浮卡的文本来自每个形状各自组的<title> DOM元素。您可以通过编辑DOM并修改标题之一来辨别:将鼠标悬停在图形上时,会看到一个新文本。

因此,我们只需要从此处和send it to the clipboard中抓取文本。

(function addListeners() {
  for (const el of document.querySelectorAll('.graph g')) {
    el.addEventListener('click', event => {
      event.stopPropagation();
      let str = "";
      for (const child of el.children) {
        if (child.nodeName != 'title') continue;
        str = child.innerHTML;
      }

      const ta = document.createElement('textarea');
      ta.value = str;
      ta.setAttribute('readonly', '');
      ta.style = { position: 'absolute', left: '-9999px' };
      document.body.appendChild(ta);
      ta.select();
      document.execCommand('copy');
      document.body.removeChild(ta);

      console.log(`"${str}" copied to clipboard!`);
    });
  }
})();

我在您所链接页面的Chrome开发者控制台中对此进行了测试,并且工作正常。

© www.soinside.com 2019 - 2024. All rights reserved.