欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS實現(xiàn)一鍵復制

 更新時間:2022年07月01日 15:13:42   作者:莎莉哇  
這篇文章主要為大家詳細介紹了js實現(xiàn)點擊按鈕復制文本,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

原生js實現(xiàn)點擊按鈕復制文本,供大家參考,具體內容如下

最近遇到一個需求,需要點擊按鈕,復制 聊天記錄的文本到剪切板

一、原理分析

瀏覽器提供了 copy 命令 ,可以復制選中的內容

document.execCommand("copy")

如果是輸入框,可以通過 select() 方法,選中輸入框的文本,然后調用 copy 命令,將文本復制到剪切板

但是 select() 方法只對 和 有效,對于就不好使

最后我的解決方案是,在頁面中添加一個 ,然后把它隱藏掉點擊按鈕的時候,先把 的 value 改為的 innerText,然后復制 中的內容

二、代碼實現(xiàn)

<style type="text/css">
? ?.wrapper {position: relative;}
? ?#input {position: absolute;top: 0;left: 0;opacity: 0;z-index: -10;}
</style>

<div class="wrapper">
? ?<p id="text">我把你當兄弟你卻想著復制我?</p>
? ?<textarea id="input">這是幕后黑手</textarea>
? ?<button onclick="copyText()">copy</button>
</div>
<script type="text/javascript">
? ? function copyText() {
? ? ? var text = document.getElementById("text").innerText;
? ? ? var input = document.getElementById("input");
? ? ? input.value = text; // 修改文本框的內容
? ? ? input.select(); // 選中文本
? ? ? document.execCommand("copy"); // 執(zhí)行瀏覽器復制命令
? ? ? alert("復制成功");
? ? }
? ? //或者
? ? function copyText(value) {
? ? ? ? // 創(chuàng)建元素用于復制
? ? ? ? var aux = document.createElement("input");

? ? ? ? // 設置元素內容
? ? ? ? aux.setAttribute("value", value);

? ? ? ? // 將元素插入頁面進行調用
? ? ? ? document.body.appendChild(aux);

? ? ? ? // 復制內容
? ? ? ? aux.select();

? ? ? ? // 將內容復制到剪貼板
? ? ? ? document.execCommand("copy");

? ? ? ? // 刪除創(chuàng)建元素
? ? ? ? document.body.removeChild(aux);

? ? ? ? //提示
? ? ? ? alert("復制內容成功:" + aux.value);
? ? }
? </script>

三、一鍵復制

分享一個自己工作中用到的一鍵復制方法

/**
?* 一鍵粘貼
?* @param ?{String} id [需要粘貼的內容]
?* @param ?{String} attr [需要 copy 的屬性,默認是 innerText,主要用途例如賦值 a 標簽上的 href 鏈接]
?*
?* range + selection
?*
?* 1.創(chuàng)建一個 range
?* 2.把內容放入 range
?* 3.把 range 放入 selection
?*
?* 注意:參數(shù) attr 不能是自定義屬性
?* 注意:對于 user-select: none 的元素無效
?* 注意:當 id 為 false 且 attr 不會空,會直接復制 attr 的內容
?*/
copy (id, attr) {
? ? let target = null;

? ? if (attr) {
? ? ? ? target = document.createElement('div');
? ? ? ? target.id = 'tempTarget';
? ? ? ? target.style.opacity = '0';
? ? ? ? if (id) {
? ? ? ? ? ? let curNode = document.querySelector('#' + id);
? ? ? ? ? ? target.innerText = curNode[attr];
? ? ? ? } else {
? ? ? ? ? ? target.innerText = attr;
? ? ? ? }
? ? ? ? document.body.appendChild(target);
? ? } else {
? ? ? ? target = document.querySelector('#' + id);
? ? }

? ? try {
? ? ? ? let range = document.createRange();
? ? ? ? range.selectNode(target);
? ? ? ? window.getSelection().removeAllRanges();
? ? ? ? window.getSelection().addRange(range);
? ? ? ? document.execCommand('copy');
? ? ? ? window.getSelection().removeAllRanges();
? ? ? ? console.log('復制成功')
? ? } catch (e) {
? ? ? ? console.log('復制失敗')
? ? }

? ? if (attr) {
? ? ? ? // remove temp target
? ? ? ? target.parentElement.removeChild(target);
? ? }
}

實現(xiàn)效果:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論