原生JS監聽複製事件,更改複製的內容,或者在複製內容後面追加參數,原生JS控制按鈕點擊複製自定義內容,複製想要讓複製的內容

原生 JS 監聽 複製 copy 事件,追加版權信息

<div class="empty-font">選中這一段文字,點擊 ctrl+C 或 者右鍵選擇複製</div>
<script type="text/javascript">
	//監聽整個頁面的 copy 事件
	document.addEventListener('copy',function(e){
		// clipboardData 對象是爲通過編輯菜單、快捷菜單和快捷鍵執行的編輯操作所保留的,也就是你複製或者剪切內容
		let clipboardData = e.clipboardData || window.clipboardData;
		// 如果 未複製或者未剪切,直接 return 
		if(!clipboardData) return ;
		// Selection 對象 表示用戶選擇的文本範圍或光標的當前位置。
		// 聲明一個變量接收 -- 用戶輸入的剪切或者複製的文本轉化爲字符串
		let text = window.getSelection().toString();
		if(text){
			// 如果文本存在,首先取消默認行爲
			e.preventDefault();
			// 通過調用 clipboardData 對象的 setData(format,data) 方法,設置相關文本 
			// format 一個 DOMString 類型 表示要添加到 drag object 的拖動數據的類型
			// data 一個 DOMString 表示要添加到 drag object 的數據
			clipboardData.setData('text/plain', text + '\r\n這是追加的版權內容')
		}
	})
</script>

原生 JS 點擊按鈕複製自定義內容:

<button type="button" onclick="copyTxt('這是複製的內容')">複製內容</button>
<script type="text/javascript">
	//原生js實現複製內容到剪切板,兼容pc、移動端(支持Safari瀏覽器)
	function copyTxt(text){
		if(typeof document.execCommand!=="function"){
			alert("複製失敗,請長按複製");
			return;
		}
		var dom = document.createElement("textarea");
		dom.value = text;
		dom.setAttribute('style', 'display: block;width: 1px;height: 1px;');
		document.body.appendChild(dom);
		dom.select();
		var result = document.execCommand('copy');
		document.body.removeChild(dom);
		if (result) {
			alert("複製成功");
			return;
		}
		if(typeof document.createRange!=="function"){
			alert("複製失敗,請長按複製");
			return;
		}
		var range = document.createRange();
		var div=document.createElement('div');
		div.innerHTML=text;
		div.setAttribute('style', 'height: 1px;fontSize: 1px;overflow: hidden;');
		document.body.appendChild(div);
		range.selectNode(div);
		const selection = window.getSelection();
		if (selection.rangeCount > 0){
			selection.removeAllRanges();
		}
		selection.addRange(range);
		document.execCommand('copy');
		alert("複製成功")
	}
</script>

參考鏈接:
https://www.cnblogs.com/rwxwsblog/p/13044142.html
https://www.cnblogs.com/zhaohongcheng/p/12208492.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章