這兩天在作跨瀏覽器的粘貼、複製、剪切功能。javascript
本覺得是很簡單的事,原來並不簡單。html
網上查了不少資料。都是跨瀏覽器把文本複製到剪切板的實現方案(zero clipboard.js)。沒有跨瀏覽器粘貼的。java
後來想到,能不能不用剪切板,而是純js。用一個全局變量存放選中的文本,再在光標所在處粘貼。chrome
網上一查,有相似的例子。因而小修下,分享之。瀏覽器
能夠兼容ie789 chrome firefox safari等測試
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>copy&past</title> <script type="text/javascript"> var selecttext=""; function InsertString(tbid){ var str = selecttext; var tb = document.getElementById(tbid); tb.focus(); if (document.all){ var r = document.selection.createRange(); document.selection.empty(); r.text = str; r.collapse(); r.select(); } else{ var newstart = tb.selectionStart+str.length; tb.value=tb.value.substr(0,tb.selectionStart)+str+tb.value.substring(tb.selectionEnd); tb.selectionStart = newstart; tb.selectionEnd = newstart; } } function GetSelection(tbid){ var sel = ''; if (document.all){ var r = document.selection.createRange(); document.selection.empty(); sel = r.text; } else{ var tb = document.getElementById(tbid); // tb.focus(); var start = tb.selectionStart; var end = tb.selectionEnd; sel = tb.value.substring(start, end); } return sel; } function ShowSelection(tbid){ var sel = GetSelection(tbid); if (sel){ alert('你選中的文本是 : '+sel); selecttext=sel; }else { alert('未選中文本'); } } </script> </head> <body> <form><textarea id="txtContent" cols="50" rows="5">這裏是一些內容,你能夠測試複製和粘貼 http://witmax.cn</textarea><br /><br /> <input type = "button" value = "複製" onclick="ShowSelection('txtContent');"/><br /> <input type = "button" value = "粘貼" onclick="InsertString('txtContent');"/> <div id="tip"></div> </form> </body> </html>