失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > php点击复制按钮到我的粘贴板 JS 实现点击按钮复制内容到粘贴板 clipboard

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

时间:2023-11-30 11:38:04

相关推荐

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 定位到窗口之外)

* - 链接: /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大体一样

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

*/

/**

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

*

* 注意事项:

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

* - 链接: /en-US/docs/Web/API/Clipboard

* - 链接: /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 = "网址复制失败!";

});

}

如果觉得《php点击复制按钮到我的粘贴板 JS 实现点击按钮复制内容到粘贴板 clipboard》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。