【JavaScript】獲取到選中的文字、複製選中的文字
阿新 • • 發佈:2019-01-10
前言:兩個小技巧
一、輸出選中的文字內容
<body> <div id="content" style="width:300px; margin:50px;"> 確認過眼神 我遇上對的人<br /> 我策馬出征 馬蹄聲如淚奔<br /> 青石板上的月光照進這山城<br /> 我一路的跟 你輪迴聲 我對你用情極深<br /> 洛陽城旁的老樹根<br /> 像回憶般延伸你問<br /> 經過是誰的心跳聲<br /> 我拿醇酒一罈飲恨<br /> 你那千年眼神是我<br /> 醉醉墜入赤壁的 傷痕<br /> 確認過眼神 我遇上對的人<br /> </div> <script> var oContent =document.getElementById('content'); oContent.onmouseup = function(){ alert(selectText()); }; function selectText(){ if(document.Selection){ //ie瀏覽器 return document.selection.createRange().text; }else{ //標準瀏覽器 return window.getSelection().toString(); } } </script> </body>
二、複製選中的文字內容
<body> <div id="content" style="width:300px; margin:50px;"> 確認過眼神 我遇上對的人<br /> 我策馬出征 馬蹄聲如淚奔<br /> 青石板上的月光照進這山城<br /> 我一路的跟 你輪迴聲 我對你用情極深<br /> 洛陽城旁的老樹根<br /> 像回憶般延伸你問<br /> 經過是誰的心跳聲<br /> 我拿醇酒一罈飲恨<br /> 你那千年眼神是我<br /> 醉醉墜入赤壁的 傷痕<br /> 確認過眼神 我遇上對的人<br /> </div> <script> var oContent =document.getElementById('content'); oContent.onmouseup = function(){ document.execCommand("Copy"); alert("複製成功") }; </script>
選取文字,擡起滑鼠後,就能對選中的文字進行復制到剪下板了,可以在其他地方貼上。
①小技巧:全選input標籤裡面的所有文字,並全部複製
<body> <input id="content" type="text" value="123456789" /> <script> var oContent =document.getElementById('content'); oContent.onfocus = function(){ oContent.select(); document.execCommand("Copy"); alert("複製成功") }; </script> </body>
②相容性
檢視下API,發現對於document.execCommand("Copy");的相容性並不是很完美,特別是移動端上。
③推薦外掛clipboard.js
<body>
<div style="">
<input type="text" id="id_text" value="123456789">
<button type="button" id="id_copy" data-clipboard-target="#id_text" data-clipboard-action="copy">點選複製</button>
</div>
<script src="https://cdn.bootcss.com/clipboard.js/1.5.15/clipboard.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
<script>
$(function(){
var clipboard = new Clipboard("#id_copy");
clipboard.on("success",function (element) {//複製成功的回撥
console.log("複製成功,複製內容:" + element.text);
});
});
</script>
對於大多數移動端瀏覽器該外掛相容效果都不錯,測試了蠻多瀏覽器,只在UC瀏覽器上遇到出現無法複製問題。(如果還有其他朋友在其他瀏覽器遇到問題,麻煩告知)。