复制绝对 URL,包括单击按钮时的 div id

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

在我的网站中,每个 h2 标签都包含复制到剪贴板图标,因此当我点击复制图标按钮时,URL 应该复制,包括 div id。

例如,绝对 URL 是“mysite dot com”,div id 是“process-invoices”,因此当我单击复制按钮时,URL 应像这样复制“mysite.com/#process-invoices”

<div class="wrapper" id="process-invoices">
  <h1>Process invoices</h1>
  <button onclick="copy absolute url with above div id value">Copy to Clipboard</button>
</div>
javascript
1个回答
0
投票

这应该适合您的目的!

function copyToClipboard(text) {
  const textarea = document.createElement("textarea");
  textarea.value = text;
  document.body.appendChild(textarea);
  textarea.select();
  try {
    const successful = document.execCommand("copy");
    const msg = successful ? "successful" : "unsuccessful";
    console.log("Copying text command was " + msg);
  } catch (err) {
    console.error("Unable to copy", err);
  }
  document.body.removeChild(textarea);
}

document.querySelector(".copy-button").addEventListener("click", function () {
  const divId = this.closest(".wrapper").id;
  const urlToCopy = `${window.location.href}#${divId}`;
  copyToClipboard(urlToCopy);
});

console.log("loaded script");
<div class="wrapper" id="process-invoices">
  <h1>Process invoices</h1>
  <button class='copy-button'>Copy to Clipboard</button>
</div>

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