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

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

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

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

问题:是否可以选择标签或添加一些JavaScript以将弹出窗口的文本复制到剪贴板?

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

谢谢。

修改:到目前为止已尝试执行操作。

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

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

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

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

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

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

因此,我们只需要从那里抓取文本,然后send it to the clipboard

编辑:这现在应该更容易运行。它只需要等到SVG的g.graph元素加载到页面上,而不是每次呈现时都可以。

(function addListener() {
  // This time,add the listener to the graph itself
  document.querySelector('.graph').addEventListener('click',event => {
    let str = ""
    // Grab all the siblings of the element that was actually clicked on
    for (const sibling of event.target.parentElement.children) {
      // Check if they're the title
      if (sibling.nodeName != 'title') continue;
      str = sibling.innerHTML;
      break;
    }

    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);

    if (str == "") console.log('Nothing found to copy!');
    else console.log(`"${str}" copied to clipboard!`);
  });
})();

如果要将其放在页面的源代码中,而不是粘贴到Chrome控制台,则摆脱函数声明并将其从括号中删除。加载文件时,它将突出运行。


原始解决方案:

// Function wrapped in brackets and called immediately after declaration
// (so that it can be run from the Chrome console):
(function addListeners() {
  // Grab every SVG 'group' in the 'graph' group:
  for (const el of document.querySelectorAll('.graph g')) {
    // Tell each group to listen for a click on itself:
    el.addEventListener('click',event => {
      // Create an empty string variable to store the title in
      let str = "";
      // Loop through all the elements in the group for one called 'title'
      for (const child of el.children) {
        if (child.nodeName != 'title') continue;
        // Store that title
        str = child.innerHTML;
      }

      // Copy the string to the clipboard (see link above)
      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开发者控制台中对此进行了测试,并且效果很好。

本文链接:https://www.f2er.com/3153065.html

大家都在问