JavaScript實現(xiàn)一鍵復(fù)制內(nèi)容剪貼板
更新時間:2022年07月22日 14:45:51 作者:TANKING
這篇文章主要為大家介紹了JavaScript實現(xiàn)一鍵復(fù)制內(nèi)容,document.execCommand原生JS設(shè)置剪貼板的實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
引言
有時候為了方便用戶快速復(fù)制頁面的內(nèi)容,一般的做法就是添加一個按鈕給用戶點擊一下就復(fù)制下來了,這邊使用JavaScript原生的方法進(jìn)行設(shè)置剪貼板。
代碼
copy.html
<!DOCTYPE html>
<html>
<head>
<title>一鍵復(fù)制demo</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0,viewport-fit=cover">
<style type="text/css">
*{
padding:0;
margin:0;
}
h2{
text-align: center;
margin-top: 20px;
}
#neirong{
width: calc(90% - 20px);
padding:10px 10px;
margin:20px auto;
background: #eee;
border-radius: 5px;
}
#copy{
border:none;
width: 90%;
height: 45px;
background: #39f;
font-size: 16px;
color: #fff;
font-weight: bold;
border-radius: 5px;
margin: 0 auto;
display: block;
}
</style>
</head>
<body>
<h2>一鍵復(fù)制demo</h2>
<div id="neirong">這是內(nèi)容這是內(nèi)容這是內(nèi)容這是內(nèi)容</div>
<button id="copy">復(fù)制</button>
<script>
function copyArticle(event){
const range = document.createRange();
range.selectNode(document.getElementById('neirong'));
const selection = window.getSelection();
if(selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
alert("復(fù)制成功");
}
window.onload = function () {
var obt = document.getElementById("copy");
obt.addEventListener('click', copyArticle, false);
}
</script>
</body>
</html>實現(xiàn)效果

以上就是JavaScript實現(xiàn)一鍵復(fù)制內(nèi)容剪切板的詳細(xì)內(nèi)容,更多關(guān)于JavaScript一鍵復(fù)制內(nèi)容的資料請關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:
- JS復(fù)制到剪貼板示例代碼
- 用js將內(nèi)容復(fù)制到剪貼板兼容瀏覽器
- js實現(xiàn)點擊后將文字或圖片復(fù)制到剪貼板的方法
- JavaScript實現(xiàn)復(fù)制或剪切內(nèi)容到剪貼板功能的方法
- JS實現(xiàn)復(fù)制內(nèi)容到剪貼板功能兼容所有瀏覽器(推薦)
- js復(fù)制內(nèi)容到剪貼板代碼,js復(fù)制代碼的簡單實例
- js實現(xiàn)各種復(fù)制到剪貼板的方法(分享)
- JS實現(xiàn)復(fù)制內(nèi)容到剪貼板功能
- JavaScript復(fù)制內(nèi)容到剪貼板的兩種常用方法
- JavaScript復(fù)制文案到剪貼板小技巧
- vue中js實現(xiàn)點擊復(fù)制文本到剪貼板的3種方案
- JS 實現(xiàn)復(fù)制到剪貼板的幾種方式小結(jié)
相關(guān)文章
微信小程序 動態(tài)綁定事件并實現(xiàn)事件修改樣式
這篇文章主要介紹了微信小程序 動態(tài)綁定事件并實現(xiàn)事件修改樣式的相關(guān)資料,需要的朋友可以參考下2017-04-04
Css-In-Js實現(xiàn)classNames庫源碼解讀
這篇文章主要為大家介紹了Css-In-Js實現(xiàn)classNames庫源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
2022-12-12
關(guān)于JavaScript輪播圖的實現(xiàn)
這篇文章主要介紹了關(guān)于JavaScript輪播圖的實現(xiàn),下面文章主要是利用利用html 和 css 代碼實現(xiàn)輪播圖,詳細(xì)內(nèi)容請參考下面詳細(xì)內(nèi)容,希望對你有所幫助
2021-11-11 
