获取手动选择的文字:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <textarea id="content" cols="30" rows="10">my name is yangkang!</textarea> <button id="btn">获取选中的文字</button> <div id="show"></div> <script> function selectText(id) { var oBox = document.getElementById(id); if(window.getSelection){ if(oBox.selectionStart != undefined && oBox.selectionEnd != undefined){ return oBox.value.substring(oBox.selectionStart,oBox.selectionEnd); } else{ return ""; } } else{ return document.selection.createRange().text; } } document.getElementById('btn').onclick = function () { document.getElementById('show').innerHTML = selectText('content'); } </script> </body> </html>
自动选中文字:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id="myTxt">my name is yangk!</div> <script> function selectText(element) { var text = document.getElementById(element); if(document.body.createTextRange){ var range = document.body.createTextRange(); range.moveToElementText(text); range.select(); } else if(window.getSelection){ var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(text); selection.removeAllRanges(); selection.addRange(range); /*if(selection.setBaseAndExtent){ selection.setBaseAndExtent(text, 0, text, 1); }*/ } else{ alert("none"); } } selectText("myTxt"); </script> </body> </html>
zclip插件(服务器环境下使用):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="jquery-1.11.1.js"></script> <script src="jquery.zclip.min.js"></script> <script> $(function(){ $('#copyBtn').zclip({ path: 'ZeroClipboard.swf', copy: function(){//复制内容 return $('#myTxt').val(); //return $('#myTxt').text();//如果是div等非能输入元素 }, afterCopy: function(){//复制成功 $("<span id='msg'/>").insertAfter($('#copyBtn')).text('复制成功'); } }); }); </script> </head> <body> <textarea id="myTxt">请输入内容</textarea><br/> <a href="javascript:;" id="copyBtn">复制内容</a> </body> </html>
execCommand
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <p>点击复制后在右边textarea CTRL+V看一下</p> <!-- 输入框 --> <input type="text" id="inputText" value="测试文本"/> <!-- 按钮 --> <input type="button" id="btn" value="复制"/> <textarea rows="4"></textarea> <script type="text/javascript"> var btn = document.getElementById('btn'); btn.addEventListener('click', function(){ var inputText = document.getElementById('inputText'); // currentFocus 是复制按钮 var currentFocus = document.activeElement; // 全选 inputText.focus(); inputText.setSelectionRange(0, inputText.value.length); // 复制 document.execCommand('copy', true); // 把光标从 inputText 中移出 currentFocus.focus(); }); </script> </body> </html>