js点击一键复制

末蓝、 2023-10-11 12:31 92阅读 0赞
  1. function copyText() {
  2. var Url2 = $(".copy-text").text();//这个是被复制的文本
  3. console.log(Url2);//打印判断
  4. var oInput = document.createElement('input');
  5. oInput.value = Url2;
  6. document.body.appendChild(oInput);
  7. oInput.select();
  8. document.execCommand("Copy");
  9. oInput.className = 'oInput';
  10. oInput.style.display = 'none';
  11. document.body.removeChild(oInput);
  12. }

上面这种写法本人测试不兼容ios一键复制

下面兼容ios

  1. <p class="cash_num">测试:
  2. <input style="border: none;display: inline-block;" type="text" id="clip_num" value="公众号wander_yun">
  3. <span style="font-size:0.21739rem;background: #6399ae;color: #f4d345;font-weight: bold;padding: 0.05435rem;" id="clip_button" onClick="copyNum()">点击复制</span>
  4. </p>
  5. // 思路:要想复制到剪贴板,必须先选中这段文字。
  6. function copyNum(){
  7. var NumClip=document.getElementById("clip_num");
  8. var NValue=NumClip.value;
  9. var valueLength = NValue.length;
  10. selectText(NumClip, 0, valueLength);
  11. if(document.execCommand('copy', false, null)){
  12. document.execCommand('copy', false, null)// 执行浏览器复制命令
  13. console.log("已复制,赶紧分享给朋友吧");
  14. }else{
  15. console.log("不兼容");
  16. }
  17. }
  18. // input自带的select()方法在苹果端无法进行选择,所以需要自己去写一个类似的方法
  19. // 选择文本。createTextRange(setSelectionRange)是input方法
  20. function selectText(textbox, startIndex, stopIndex) {
  21. if(textbox.createTextRange) {//ie
  22. var range = textbox.createTextRange();
  23. range.collapse(true);
  24. range.moveStart('character', startIndex);//起始光标
  25. range.moveEnd('character', stopIndex - startIndex);//结束光标
  26. range.select();//不兼容苹果
  27. }else{//firefox/chrome
  28. textbox.setSelectionRange(startIndex, stopIndex);
  29. textbox.focus();
  30. }
  31. }

发表评论

表情:
评论列表 (有 0 条评论,92人围观)

还没有评论,来说两句吧...

相关阅读

    相关 js实现按钮复制文本功能

    最近遇到一个需求,需要点击按钮,复制 <p> 标签中的文本到剪切板 之前做过复制输入框的内容,原以为差不多,结果发现根本行不通 尝试了各种办法,最后使了个障眼法,实现了下面