本文已参与「新人创作礼」活动,一起开启掘金创作之路。
需求需实现一键复制当前网址链接功能,通过获取domain域名+路由参数this.props.location的pathname和search参数拼接获得当前网址,再使用document.execCommand实现复制功能
iosCopy: function () {
window.getSelection().removeAllRanges();//这段代码必须放在前面否则无效
var input = document.createElement("input");
document.body.appendChild(input);
input.setAttribute("value", 要复制的值);
input.select();
var range = document.createRange();
// 选中需要复制的节点
range.selectNode(input);
// 执行选中元素
window.getSelection().addRange(range);
input.select();
input.setSelectionRange(0, input.value.length);//适配高版本ios
// 执行 copy 操作
document.execCommand('copy');
// 移除选中的元素
window.getSelection().removeAllRanges();
document.body.removeChild(input);
}
androidCopy: function () {
var input = document.createElement("input");
document.body.appendChild(input);
input.setAttribute("value", 要复制的值);
input.select();
if (document.execCommand("copy")) {
document.execCommand("copy");
} else {
console.log('document.execCommand用不了');
}
document.body.removeChild(input);
}