gpt4 book ai didi

javascript - 如何将按钮的内容复制到剪贴板(JS)

转载 作者:行者123 更新时间:2023-11-30 11:15:02 25 4
gpt4 key购买 nike

我希望能够将按钮的文本复制到剪贴板。我能够检索按钮的 innerText 并将其记录到控制台,但我无法将其添加到选择中,然后最终使用“document.execCommand("copy");”将其添加到剪贴板。有什么想法吗?

$(document).ready(function() {
$('button').on('click', function() {
var copyText = this.innerText;
console.log(copyText);
copyText.select;
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div>
<ul id="test">
<li>
<button class="copy-button" id="button1">Test1</button>
</li>
<li>
<button class="copy-button" id="button2">Test2</button>
</li>
<li>
<button class="copy-button" id="button3">Test3</button>
</li>
</ul>
</div>

最佳答案

好的,除了将字符串添加到剪贴板之外,您必须这样做:

创建一个textarea,将你的stiring添加到textarea,然后从那里复制,然后删除textarea。

希望对您有所帮助:

function copyStringToClipboard () {
var str = document.getElementById("btn1").innerText;
// Create new element
var el = document.createElement('textarea');
// Set value (string to be copied)
el.value = str;
// Set non-editable to avoid focus and move outside of view
el.setAttribute('readonly', '');
el.style = {position: 'absolute', left: '-9999px'};
document.body.appendChild(el);
// Select text inside element
el.select();
// Copy text to clipboard
document.execCommand('copy');
// Remove temporary element
document.body.removeChild(el);
}
<button onclick="copyStringToClipboard()" id = 'btn1'>Click me</button>
<input type="text" placeholder="Paste here">

关于javascript - 如何将按钮的内容复制到剪贴板(JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51966085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com