原生js/jQuery实现一键复制本页面链接到剪切板

jQuery实现复制本页面链接到剪切板

最近做项目,刚好学到这个知识点
首先,分两个步骤:

  1. 获取本页面的url
  2. 复制到剪切板
  1. 获取本页面的url一般是使用这个语句
window.location.href
  1. 复制文本到剪切板

这里用到一个方法:document.execCommand()
其官方解释是:

在这里插入图片描述

“可编辑区域” 即 input / textarea

所以这个方法的步骤为:

  • 创建input / textarea 标签 ,其value 为想要复制的内容,比如这篇文章的本页面url
  • 添加input / textarea 标签到页面的任何一个地方(如果不想看见就可以display:none;)
  • 使用element.select()方法选择input/textarea 标签
  • 使用Document.execCommand(“copy”);方法复制value的内容到剪切板
  • 把添加的input / textarea 标签移除

接下来展示完整下代码

//1.原生js
var input = document.createElement("input");
var  body = document.body;
body.appendChild(input);
input.value = window.location.href;
input.select();
document.exeCommand("copy");
body.removeChild(input);
//2.jQuery
    var input = $("<input value = " + window.location.href + ">");
    $("body").prepend(input);
    $("body").find("input").eq(0).select();
    document.exeCommand("copy");
    $("body").find("input").eq(0.remove();

注:select()方法,选择一定要准确选择到相应的input标签

猜你喜欢

转载自blog.csdn.net/piaoliangj/article/details/109480254
今日推荐