javascript - 将 URL 复制到剪贴板并显示和隐藏消息
问题描述
想将当前 URL 复制到剪贴板显示通知消息并在几秒钟后再次隐藏。我在网上看到过这个功能。
动画 gif 显示了它应该如何工作。Javascript 部分是从具有工作示例的网站中提取的,并且使用了相同的 HTML 和 CSS 代码,但 javascript 的格式尚未正确,因为我只提取了该函数需要的部分。有人可以帮我正确编写javascript吗?小提琴准备好了:
提取的 javascript
events: {
"click .share": "onShareClick"
},
onMouseEnter: function() {},
onShareClick: function(e) {
var t = this;
this.$el.find(".share").addClass("show-notice"), setTimeout(function() {
t.$el.find(".share").removeClass("show-notice")
}, 3e3);
var n = document.createElement("textarea");
n.value = location.href, document.body.appendChild(n), n.select(), document.execCommand("copy"), document.body.removeChild(n)
},
HTML
<div class="share">
<img src="images/share.svg">
<span class="share-notice">Link copied to clipboard</span>
<span class="mouseenter-notice">Share</span>
</div>
解决方案
假设 div 是文档中“share”类的第一个成员,您可以尝试:
const div = document.getElementsByClassName('share')[0];
const shareNotice = document.getElementById('share-notice');
const mouseoverNotice = document.getElementById('mouseover-notice');
div.onclick = () => {
window
.navigator
.clipboard
.writeText(window.location.href);
shareNotice.style.display = 'initial';
window.setTimeout(() => shareNotice.style.display = 'none', 1500);
};
div.onmouseover = () => mouseoverNotice.style.display = 'initial';
div.onmouseleave = () => mouseoverNotice.style.display = 'none';
.share { cursor: pointer }
#share-notice { display: none; }
#mouseover-notice { display: none; }
<div class="share">
x
<span id="share-notice">Link copied to clipboard</span>
<span id="mouseover-notice">Share</span>
</div>
推荐阅读
- reactjs - 如何修复:错误:ENOENT:没有这样的文件或目录 'src/node_modules/native-base/Fonts'
- git - 需要在 `git log` 上设置哪些标志以使其具有与 `git whatchanged` 相似的输出?
- voip - 提取音频并将其注入正在进行的 VOIP 呼叫
- oop - 如何在复杂的纸牌游戏中平衡多态/继承/TypeData架构与原型/享元模式的技巧?
- ios - 从 Game Center API 检索其他游戏的数据
- jupyter-notebook - ipywidgets:更改小部件值后自动更新变量并运行代码
- python-3.x - python:bz2“增量”和“一次性”(去)压缩与“常规”方法有何不同?
- r - R 使用 lapply 保存图
- xml - 大家好,我在 ActivityMain.xml 的屏幕预览中遇到了丢失标题栏的问题
- html - 让屏幕阅读器读出 div 中的所有文本