首页 > 代码库 > 选中/复制文字

选中/复制文字

获取手动选择的文字:

<!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>

 

选中/复制文字