【问题标题】:Can't download or copy SVG without body element无法下载或复制没有正文元素的 SVG
【发布时间】:2020-10-18 06:42:05
【问题描述】:

如何成功地将本页的 SVG 内容复制到剪贴板?

https://cdn.dribbble.com/assets/dribbble-ball-icon-e94956d5f010d19607348176b0ae90def55d61871a43cb4bcb6d771d8d235471.svg

select() 方法出现如下错误:

Uncaught TypeError: el.select is not a function
    at <anonymous>:1:4

这是我目前可以在控制台中运行的代码。

function copyClip() {
  const docEl = document.documentElement
  const string = new XMLSerializer().serializeToString(docEl)
  const el = document.createElement('textarea')
  docEl.insertAdjacentElement('beforeend', el)
  el.value = string
  el.select()
  document.execCommand('copy')
}

copyClip()

【问题讨论】:

标签: javascript xml svg clipboard


【解决方案1】:

对此的一个答案是使用不同的复制到剪贴板执行,但我不明白为什么原始问题中的 select 方法不起作用。此功能有效:

const docEl = document.documentElement
    const string = new XMLSerializer().serializeToString(docEl)
    navigator.clipboard.writeText(string).then(
      function () {
        alert('The SVG was copied to your clipboard.')
      },
      function (err) {
        alert('Could not copy:', err)
      }
    )

【讨论】:

    猜你喜欢
    • 2019-09-20
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    相关资源
    最近更新 更多