目錄
背景
核心代碼
案例文章來源:http://www.zghlxwxcb.cn/news/detail-660185.html
背景
我們開發(fā)中可能會有點擊復(fù)制的功能,那么下面將講述文章來源地址http://www.zghlxwxcb.cn/news/detail-660185.html
核心代碼
-
select()
方法用于選擇該元素中的文本。 -
document.execCommand('copy')
執(zhí)行瀏覽器復(fù)制命令
案例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
.wrapper {
position: relative;
}
#input {
position: absolute;
top: 0;
left: 0;
opacity: 0;
z-index: -10;
}
</style>
</head>
<body>
<div class="wrapper">
<p id="text" onclick="copyText()">復(fù)制的一段文字</p>
<input id="input" value="躲起來的文本框"/>
<!-- <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; // 修改文本框的內(nèi)容
input.select(); // 選中文本
document.execCommand("copy"); // 執(zhí)行瀏覽器復(fù)制命令
alert("復(fù)制成功");
}
</script>
</body>
</html>
到了這里,關(guān)于(簡單成功)原生js實現(xiàn)點擊復(fù)制文本的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!