首页 > 解决方案 > 识别锚点并将 URL 复制到剪贴板

问题描述

我有这种格式的长文档页面:

<div class="guides-chapter">
  <h3 id="oranges">Oranges are great</h3>
  <button class="clipboard-guide">Copy link</button>
  <div class="copied"></div>
</div>
...
<div class="guides-chapter">
  <h3 id="apples">Apples are great</h3>
  <button class="clipboard-guide">Copy link</button>
  <div class="copied"></div>

</div>
...

单击按钮时,我正在尝试使用 jQuery 实现以下目标:

  1. 确定 H3 的标题以用作 # 锚点
  2. 在复制之前从当前 URL 中删除任何现有的 # 锚点
  3. 将 URL + # 放入剪贴板
  4. 将文本 'URL 复制' 放入 div.copied

回复 2:如果有人通过锚点(例如 index.html#oranges)到达页面,然后想要复制 #apples 下的 URL,这是必要的。在这种情况下,必须首先删除#oranges。

我试图以这个脚本为基础,但我很迷茫。任何人都可以帮助我?

标签: javascriptjquery

解决方案


window.location.origin您可以使用和的组合获取没有当前哈希的 URL window.location.pathname。然后您可以使用它$.siblings()来查找兄弟姐妹<h3>$.attr()获取其 ID。

你的副本走在了正确的轨道上,但你可以做得更好。我已经将副本创建为一个函数。它与您笔中的内容非常相似,但它需要一个参数来确定您要复制的文本。

如果复制因任何原因失败,它将显示用户可以手动复制的文本提示,如果失败,它将静默记录到控制台。

function copyText(text, elm)
{
  let textarea = document.createElement("textarea");
  textarea.value = text;
  textarea.style.position="fixed";
  textarea.style.opacity=0.01;
  document.body.appendChild(textarea);
  textarea.focus();
  textarea.select();
  
  try {
    let success = document.execCommand("copy");
    document.body.removeChild(textarea);
    if(success)
    {
      if(elm != undefined)
        elm.siblings(".copied").html("text copied!");
    }
    else
    {
      prompt("Press Ctrl+C to copy (Cmd+C on Mac)", text);
    }
  } catch (error) {
    console.log("Unable to copy", error);
  }
}

$(".clipboard-guide").on("click", function(){
  let url = window.location.origin + window.location.pathname;
  let toCopy = `${url}#${$(this).siblings("h3").attr("id")}`;
  copyText(toCopy, $(this));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="guides-chapter">
  <h3 id="oranges">Oranges are great</h3>
  <button class="clipboard-guide">Copy link</button>
  <div class="copied"></div>
</div>

<div class="guides-chapter">
  <h3 id="apples">Apples are great</h3>
  <button class="clipboard-guide">Copy link</button>
  <div class="copied"></div>

</div>


推荐阅读