javascript - 识别锚点并将 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 实现以下目标:
- 确定 H3 的标题以用作 # 锚点
- 在复制之前从当前 URL 中删除任何现有的 # 锚点
- 将 URL + # 放入剪贴板
- 将文本 'URL 复制' 放入 div.copied
回复 2:如果有人通过锚点(例如 index.html#oranges)到达页面,然后想要复制 #apples 下的 URL,这是必要的。在这种情况下,必须首先删除#oranges。
我试图以这个脚本为基础,但我很迷茫。任何人都可以帮助我?
解决方案
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>
推荐阅读
- excel - Excel 在另一个工作簿中运行宏,在第一个工作簿上引用数据,然后将它们都关闭。只有一个会关闭
- laravel-5 - 如何使用 laravel mix 将 js 编译为 es5?
- cocoapods - 如何处理具有共同来源的 test_specs
- android - Android Studio的build gradle(app)中定义的依赖版本在哪里?
- reactjs - React 的非破坏空间?
- python - 自定义 ImageDataGenerator 行为不端
- excel - 使用 Excel VBA 创建具有特定值的行的 Outlook 电子邮件正文
- tableau-api - 计划刷新 Tableau desktop 10.4 并在特定日期/时间计划刷新
- javascript - 在 Jquery 中切换列表元素,同时始终显示前几个元素
- arrays - $elemMatch 对不包含子文档的数组有用吗?