php点击复制按钮到我的粘贴板,JS 实现点击按钮复制内容到粘贴板 clipboard

具体实现如下:

点击按钮复制内容到粘贴板

body {

text-align: center;

}

#p1 {

line-height: 150px;

font-size: 40px;

}

#source {

font-size: 18px;

}

.wrapper {

margin-top: 50px;

}

.btn {

width: 300px;

height: 120px;

background-color: #4da2fd;

color: #fff;

font-size: 20px;

text-decoration: none;

margin-top: 10px;

padding: 10px;

border-radius: 5px;

cursor: pointer;

}

#result {

width: 100%;

line-height: 30px;

color: #555;

font-size: 35px;

margin-top: 100px;

}

将要复制的内容

/**

* 方法1: 创建一个 input 标签,执行 input 的 select 方法,然后执行 document.execCommand("Copy") 实现复制

*

* 注意事项:

* - input 标签不能是 display: none; (使用定位把 input 定位到窗口之外)

* - 链接: https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

*/

function copyText() {

var inputEle = document.createElement('input');

inputEle.style.position = 'fixed';

inputEle.style.left = '100000px';

// inputEle.value = document.getElementById("source").value;

inputEle.value = document.getElementById("p1").innerText;

document.body.append(inputEle);

inputEle.select();

var isSuccess = document.execCommand("copy");

document.getElementById('result').innerText = isSuccess ? "文字复制成功!" : "文字复制失败!";

document.body.removeChild(inputEle);

}

/**

* 方法2: 使用 clipboard.js, 具体用法看对应文档

*

* 注意事项:

* - clipboard.js 实现和方法1大体一样

* - 链接: https://github.com/zenorocha/clipboard.js/tree/2b48909ff1fb6da1378a3a6bc81a61a67f629dc2

*/

/**

* 方法3: 使用 navigator.clipboard.writeText 方法实现复制

*

* 注意事项:

* - 这种方法在浏览器 console 控制台直接调用会失败

* - 链接: https://developer.mozilla.org/en-US/docs/Web/API/Clipboard

* - 链接: https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText

*/

function copyLink() {

var siteUrl = window.location.href;

navigator.clipboard.writeText(siteUrl).then(function () {

/* clipboard successfully set */

document.getElementById('result').innerText = "网址复制成功!";

}, function () {

/* clipboard write failed */

document.getElementById('result').innerText = "网址复制失败!";

});

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值