原生js實現復制內容到剪切板,兼容pc、移動端(支持Safari瀏覽器)


在開發中經常會遇到這樣的需求,第一種就是點擊復制當前頁面的鏈接,第二種就是類似卡券的功能,需要復制密碼等等。
在網上看到有很多該功能的實現代碼,除了插件clipboard.js、ZeroClipboar兼容性較好以外,其他大部分在safari,ios上的微信端這些並不兼容。那么在不使用插件的情況下,為大家整理了一份較為兼容的實現方式:純js實現復制文本並提示復制成功(干貨)適用所有瀏覽器,直接放項目就能用。 

代碼如下:

<a onclick="copyTxt('這是要復制的內容哦')">點擊復制</a>

js:

<script>
//原生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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM