1. 程式人生 > >JS實現點選複製功能(完美解決移動端可用)

JS實現點選複製功能(完美解決移動端可用)

先看一下效果圖

使用此方法不需要轉換什麼<p>標籤,直接就使用<textarea>標籤,就是把它的樣式修改了一下,將背景和邊框都改為你要的顏色就可以了

上程式碼:

//Html
<div id="code">
	<p class="main-yCode">你的邀請碼</p>
	<textarea id="copycode" class="main-code" readonly="readonly">&nbsp;</textarea>
	<div class="main-btn">
		<button onClick="copyCode()">複製</button>
	</div>
</div>


//Js
function copyCode(){
	var copycode=document.getElementById("copycode");
	copycode.select(); // 選擇物件
	document.execCommand("Copy"); // 執行瀏覽器複製命令
	alert("已複製好,可貼粘。")
}


//Css
.main-yCode {
	text-align: center;
	font-size: 16px;
	margin-top: 20px;
}
.main-code {
	text-align: center;
	font-size: 24px;
	margin-top: 20px;
	width: 100%;
	height: 40px;
	background: white;
	border: white;
	outline: none;
}
.main-btn {
	margin-top: 20px;
	text-align: center;
	font-size: 16px;
}
.main-btn button{
	color: white;
	background: blue;
	width: 70px;
	height: 24px;
}

深圳的加一下群吧,一起交流,面試內推線下活動等等

最後分享一個公眾號二維碼,寫一些散文和影評等,歡迎關注。