猿问

使用 JavaScript 将多个标签中特定标签的文本复制到剪贴板

我想使用 javascript 将输入复制到我的剪贴板,所以有什么办法可以做,谢谢

无需输入字段

JavaScript 和 HTML


function copy(input){
    }
<p>Text To Copy = hi <button type="button" onclick="copy('hi')">click to copy</button></p>


当年话下
浏览 242回答 3
3回答

慕姐8265434

您可以使用navigator.clipboard.writeText将文本复制到剪贴板。function copy(input) {&nbsp; if (navigator.clipboard) {&nbsp; &nbsp; navigator.clipboard.writeText(input).then(() => {&nbsp; &nbsp; &nbsp; console.log('Copied to clipboard successfully.');&nbsp; &nbsp; }, (err) => {&nbsp; &nbsp; &nbsp; console.log('Failed to copy the text to clipboard.', err);&nbsp; &nbsp; });&nbsp; } else if (window.clipboardData) {&nbsp; &nbsp; window.clipboardData.setData("Text", input);&nbsp; }}<p>Text To Copy = hi <button type="button" onclick="copy('hi')">click to copy</button></p>

慕姐4208626

function copy_text_fun() {&nbsp; &nbsp; //getting text from P tag&nbsp; &nbsp; var copyText = document.getElementById("copy_txt");&nbsp;&nbsp;&nbsp; &nbsp; // creating textarea of html&nbsp; &nbsp; var input = document.createElement("textarea");&nbsp; &nbsp; //adding p tag text to textarea&nbsp;&nbsp; &nbsp; input.value = copyText.textContent;&nbsp; &nbsp; document.body.appendChild(input);&nbsp; &nbsp; input.select();&nbsp; &nbsp; document.execCommand("Copy");&nbsp; &nbsp; // removing textarea after copy&nbsp; &nbsp; input.remove();&nbsp; &nbsp; alert(input.value);}<p id="copy_txt">hi</p><button&nbsp; onclick="copy_text_fun()">Copy</button>

喵喔喔

请试试这个。也许它会为你工作。&nbsp;function myFunction() {&nbsp; &nbsp; &nbsp; /* Get the text field */&nbsp; &nbsp; &nbsp; var copyText = document.getElementById("myInput");&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; /* Select the text field */&nbsp; &nbsp; &nbsp; copyText.select();&nbsp; &nbsp; &nbsp; copyText.setSelectionRange(0, 99999); /*For mobile devices*/&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; /* Copy the text inside the text field */&nbsp; &nbsp; &nbsp; document.execCommand("copy");&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; /* Alert the copied text */&nbsp; &nbsp; &nbsp; alert("Copied the text: " + copyText.value);&nbsp; &nbsp; }&nbsp;<input type="text" value="Hello World" id="myInput">&nbsp; &nbsp; <button onclick="myFunction()">Copy text</button>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答