所以我想使用 Javascript 創建一個 ClickToCopyToClipboard,當有人點擊 textarea 時,它的內容將被復制到剪貼板。但是我從 Youtube 上觀看的所有視頻都需要點擊一個按鈕。
所以這是我的 Html
<div > <textarea onclick="copytxt()">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque bibendum risus eros, eu mollis lorem consectetur eget.</textarea> </div>
這是我的 JS
```function copytxt(){
const textarea
document.querySelector("textarea");
textarea.select();
document.execCommand("copy");
};```
uj5u.com熱心網友回復:
嘗試向文本區域添加事件偵聽器,
<!DOCTYPE html>
<html>
<body>
<p>Click anywhere in the textarea to copy the text from it. Try to paste the text (e.g. ctrl v) afterwards in the input field given below, to see the effect.</p>
<textarea type="text" value="Hello World" id="myInput">
hello world!!!
</textarea>
<input type="text" />
<script>
/* Get the text field */
var copyText = document.getElementById("myInput");
copyText.addEventListener('click', () => { myFunction(); })
function myFunction() {
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /* For mobile devices */
/* Copy the text inside the text field */
navigator.clipboard.writeText(copyText.value);
/* Alert the copied text */
alert("Copied the text: " copyText.value);
}
</script>
</body>
</html>
可以在這里給出演示,但 stackoverflow 不允許復制功能。
uj5u.com熱心網友回復:
您的 JS 很接近,盡管其中存在語法錯誤(缺少=)。這是一個具有適當addEventListener樣式的作業示例,而不是行內 JS。
document.querySelector("textarea").addEventListener("click", function(){
this.select();
document.execCommand("copy");
});
<textarea readonly>click me to copy my contents</textarea>
<br><br>
Then try pasting them in here:
<input type="text"/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/348807.html
標籤:javascript html
