1. 程式人生 > >點擊復制到剪切板

點擊復制到剪切板

光標 focus mov one 內容 element end phone creat

點擊復制到剪切板,兼容性很好,可以自定義樣式,加以美化。

<!DOCTYPE html>    
<html lang="en">    
<head>    
    <meta charset="UTF-8">          
    <meta name="viewport" content="maximum-scale=1.0, minimum-scale=1.0, user-scalable=0, initial-scale=1.0, width=device-width" />
    <meta 
name="format-detection" content="telephone=no, email=no, date=no, address=no"> <title>點擊復制到剪切板</title> </head> <body> <h2>點擊粘貼出現《我被復制了》</h2> <button id="clip_button" onClick="copyNum()">點擊復制到剪切板</button><br/><br/> <!--
測試是否復制 --> <textarea></textarea> <!-- 將復制內容隱藏 --> <input type="text" id="clip_num" style="width:1px;height:1px;position:absolute;top:-10px;left:-10px" value="我被復制了"> <script> // 思路:要想復制到剪貼板,必須先選中這段文字。 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(); } } /*兼容性補充: 移動端: 安卓手機:微信(chrome)和幾個手機瀏覽器都可以用。 蘋果手機:微信裏面和sarafi瀏覽器裏也都可以, PC端:sarafi版本必須在10.2以上,其他瀏覽器可以. 兼容性測試網站:https://www.caniuse.com/ */ </script> </body> </html>

點擊復制到剪切板