使用 JavaScript 在網頁上建立“複製到剪貼簿”功能
以下是使用 JavaScript 在網頁上建立“複製到剪貼簿”功能的程式碼 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
}
input,
button {
padding: 8px;
}
</style>
</head>
<body>
<h1>Creating Copy to Clipboard</h1>
<input class="textCopy" type="text" />
<button class="Btn">Copy Text</button><br /><br />
<input type="text" placeholder="paste here" />
<h3>Click on the above button to copy text from the textbox</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
let textCopyEle = document.querySelector(".textCopy");
BtnEle.addEventListener("click", () => {
textCopyEle.select();
document.execCommand("copy");
});
</script>
</body>
</html>輸出

在第一個文字框中輸入內容並單擊“複製文字”按鈕 −

透過在“在此貼上”文字框中單擊滑鼠並選擇貼上來貼上文字 −

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式語言
C++
C#
MongoDB
MySQL
Javascript
PHP