鍍金池/ 問(wèn)答/HTML/ js 如何默認(rèn)復(fù)制一段文本?

js 如何默認(rèn)復(fù)制一段文本?

在移動(dòng)和pc端,打開(kāi)頁(yè)面,默認(rèn)復(fù)制一段文本到剪輯版,想實(shí)現(xiàn)這樣的功能該怎么寫(xiě)js代碼呢

回答
編輯回答
熊出沒(méi)

github關(guān)鍵詞 cilpboard

2018年1月6日 12:53
編輯回答
陪妳哭

你可以看看document.execCommand這個(gè)方法。

例子

An example of how to use it on CodePen.

快速實(shí)現(xiàn)復(fù)制到剪貼板:

<p>點(diǎn)擊復(fù)制后在右邊textarea CTRL+V看一下</p>
<input type="text" id="inputText" value="測(cè)試文本"/>
<input type="button" id="btn" value="復(fù)制"/>
<textarea rows="4"></textarea>
<script type="text/javascript">
    var btn = document.getElementById('btn');
    btn.addEventListener('click', function(){
        var inputText = document.getElementById('inputText');
        var currentFocus = document.activeElement;
        inputText.focus();
        inputText.setSelectionRange(0, inputText.value.length);
        document.execCommand('copy', true);
        currentFocus.focus();
    });
</script>

然而移動(dòng)端的兼容性...

Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? (Yes) (Yes) ? ? ?
insertBrOnReturn 未實(shí)現(xiàn) 未實(shí)現(xiàn) (Yes) 未實(shí)現(xiàn) 未實(shí)現(xiàn) 未實(shí)現(xiàn)
copy/cut 未實(shí)現(xiàn) 42 41.0 (41) ? ? 未實(shí)現(xiàn)
2017年12月19日 05:04
編輯回答
憶當(dāng)年

如果是用戶操作復(fù)制的話 樓上的那個(gè)document.execCommand就可以基本實(shí)現(xiàn),有一個(gè)clipboard.js插件 可以看看。 如果想用戶不主動(dòng)去觸發(fā)打開(kāi)頁(yè)面直接復(fù)制的話 移動(dòng)端暫時(shí)沒(méi)發(fā)現(xiàn)有什么好的辦法,都會(huì)被阻止

2018年8月10日 01:08
編輯回答
蝶戀花

純js的話,移動(dòng)端基本不用考慮了。兼容性非常差。

2017年11月7日 03:15