js点击一键复制
function copyText() {
var Url2 = $(".copy-text").text();//这个是被复制的文本
console.log(Url2);//打印判断
var oInput = document.createElement('input');
oInput.value = Url2;
document.body.appendChild(oInput);
oInput.select();
document.execCommand("Copy");
oInput.className = 'oInput';
oInput.style.display = 'none';
document.body.removeChild(oInput);
}
上面这种写法本人测试不兼容ios一键复制
下面兼容ios
<p class="cash_num">测试:
<input style="border: none;display: inline-block;" type="text" id="clip_num" value="公众号wander_yun">
<span style="font-size:0.21739rem;background: #6399ae;color: #f4d345;font-weight: bold;padding: 0.05435rem;" id="clip_button" onClick="copyNum()">点击复制</span>
</p>
// 思路:要想复制到剪贴板,必须先选中这段文字。
function copyNum(){
var NumClip=document.getElementById("clip_num");
var NValue=NumClip.value;
var valueLength = NValue.length;
selectText(NumClip, 0, valueLength);
if(document.execCommand('copy', false, null)){
document.execCommand('copy', false, null)// 执行浏览器复制命令
console.log("已复制,赶紧分享给朋友吧");
}else{
console.log("不兼容");
}
}
// input自带的select()方法在苹果端无法进行选择,所以需要自己去写一个类似的方法
// 选择文本。createTextRange(setSelectionRange)是input方法
function selectText(textbox, startIndex, stopIndex) {
if(textbox.createTextRange) {//ie
var range = textbox.createTextRange();
range.collapse(true);
range.moveStart('character', startIndex);//起始光标
range.moveEnd('character', stopIndex - startIndex);//结束光标
range.select();//不兼容苹果
}else{//firefox/chrome
textbox.setSelectionRange(startIndex, stopIndex);
textbox.focus();
}
}
还没有评论,来说两句吧...