首页 > 解决方案 > 将 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>

标签: javascripthtmlcssurlclipboard

解决方案


假设 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>


推荐阅读