页面有多个id=txt,现在只有第一个有效。
我希望都有效,能实现吗?
谢谢。
<button onclick="copy()">复制1</button>
<p id="txt">第一段内容</p>
<textarea name="" id="jsTextArea" cols="30" rows="10" style='opacity: 0;position: absolute;' ></textarea>
<button onclick="copy()">复制2</button>
<p id="txt">第二段内容 </p>
<script type="text/javascript">
function copy() {
const copyElement = document.getElementById('txt');
const textareaElement = document.getElementById('jsTextArea');
textareaElement.innerText = copyElement.innerHTML;
textareaElement.select();
document.execCommand('copy');
}
</script>
id 选择器是唯一的,同一个 id 只能用一次,所以上下文只能有个id 是 txt 的元素,你多个元素用同一个 id 是不规范的
还有你的第一个 textarea 把下面的 button 按钮盖住了,导致下面的 button 按钮永远无法被点击