有個(gè)很常見的生活場(chǎng)景是:我們?cè)诰W(wǎng)頁(yè)上閱讀一篇文章,移動(dòng)鼠標(biāo),框選一段文字,這個(gè)時(shí)候文字有了藍(lán)色背景,點(diǎn)鼠標(biāo)右鍵,選擇復(fù)制,就可以把選中的文字復(fù)制到剪貼板中。 其實(shí)這一小小的行為在 JavaScript 中涉及到如下一些術(shù)語(yǔ):
相關(guān)術(shù)語(yǔ)
-
錨點(diǎn)(anchor)
錨點(diǎn)指的是一個(gè)選區(qū)的起始點(diǎn),這里的錨點(diǎn)不同于HTML中的錨點(diǎn)鏈接。當(dāng)我們使用鼠標(biāo)框選一個(gè)區(qū)域的時(shí)候,錨點(diǎn)就是我們鼠標(biāo)按下瞬間的那個(gè)點(diǎn)。在用戶拖動(dòng)鼠標(biāo)時(shí),錨點(diǎn)是不會(huì)變的。
-
焦點(diǎn)(focus)
選區(qū)的焦點(diǎn)是該選區(qū)的終點(diǎn),當(dāng)您用鼠標(biāo)框選一個(gè)選區(qū)的時(shí)候,焦點(diǎn)是你的鼠標(biāo)松開瞬間所記錄的那個(gè)點(diǎn)。隨著用戶拖動(dòng)鼠標(biāo),焦點(diǎn)的位置會(huì)隨著改變。
-
范圍(range)
范圍俗稱拖藍(lán),用來(lái)表示用戶選中的文本區(qū)域,即從錨點(diǎn)到焦點(diǎn)的這一段文本區(qū)域。
HTMLInputElement 的三種方法
-
選中文本域中的內(nèi)容
HTMLInputElement.select()
英文解釋為:Selects the input text in the element, and focuses it so the user can subsequently replace the whole entry.
剛認(rèn)識(shí)這個(gè)方法的時(shí)候,下意識(shí)的覺(jué)得應(yīng)該會(huì)返回選中的文字才對(duì),然而并沒(méi)有,這個(gè)方法沒(méi)有返回值,僅僅只是選中了文字而已。
-
在文本域上設(shè)置焦點(diǎn)
HTMLInputElement.focus()
英文解釋為:Focus on input; keystrokes will subsequently go to this element.
-
從文本域上移開焦點(diǎn)
HTMLInputElement.blur()
英文解釋為:Removes focus from input; keystrokes will subsequently go nowhere.
值得注意的是以上三種方法都只面向 <input> 和 <textarea> 結(jié)點(diǎn),并且都沒(méi)有返回值。
document.execCommand
文檔對(duì)象的 execCommand方法允許運(yùn)行命令來(lái)操縱可編輯區(qū)域的內(nèi)容,具體可以查看這里. 下面僅介紹 copy 這個(gè)方法:
bool = document.execCommand(copy)
這個(gè)方法指拷貝當(dāng)前選中內(nèi)容到剪貼板,返回值為一個(gè) bool 值, 如果返回值為 false 則表示操作不被支持或未被啟用。
很遺憾的是這個(gè)方法的瀏覽器兼容性一般,IE 僅支持 8 以上的版本。
通過(guò)以上幾個(gè)方法我們已經(jīng)可以實(shí)現(xiàn)簡(jiǎn)單的復(fù)制粘貼功能了:
<input type="text" class="box-text" value="choose me!" />
<button class="bt-copy" >copy</button>
<script>
$('.bt-copy').click(function(){
var copyTarget = $('.box-text');
copyTarget.select();
try {
document.execCommand('copy');
}
catch (err) {
alert('請(qǐng)使用CTRL+C,CTRL+V來(lái)復(fù)制粘貼~');
}
copyTarget.blur();
})
</script>
短短幾行代碼就實(shí)現(xiàn)了復(fù)制粘貼的功能,但仍然有改進(jìn)的地方:
- 增加除 <input> 和 <textarea> 外的結(jié)點(diǎn)的支持,可以借鑒 select.js 的實(shí)現(xiàn)方法。
- 對(duì)不支持
document.execCommand('copy')的瀏覽器使用 ZeroClipboard 作為 fallback。
---------------------------------------- 2017/5/5日 更 ----------------------------------------
之前說(shuō)過(guò), .select() 方法僅支持 <input> 和 <textarea> 元素,發(fā)現(xiàn)一個(gè)更好的辦法用于解決這個(gè)問(wèn)題:
- 用 js 生成一個(gè)隱藏的
<textarea>元素,追加到 dom 里面。 - 把需要復(fù)制的文本賦值給剛生成的
<textarea>元素。 - 使用原生的方法進(jìn)行選中和復(fù)制的操作。
- 最后記得在DOM中移除
<textarea>元素。
var textArea = document.createElement('textarea');
textArea.style.position = 'fixed';
textArea.style.left = '-10000px';
textArea.style.top = '-10000px';
document.body.appendChild(textArea);
textArea.value = this.copyText;
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);