页面有多个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 按钮永远无法被点击
<div class="copy-wrapper">
<button onclick="copy()">复制1</button>
<p class="copy-p">第一段内容</p>
<textarea name="" class="copy-input" cols="30" rows="10" style='opacity: 0;position: absolute; width: 0; height: 0;' ></textarea>
</div>
<div class="copy-wrapper">
<button onclick="copy()">复制2</button>
<p class="copy-p">第二段内容</p>
<textarea name="" class="copy-input" cols="30" rows="10" style='opacity: 0;position: absolute; width: 0; height: 0;' ></textarea>
</div>
function copy(e) {
const btn = event.target // 拿到当前 dom
const wrapper = btn.parentNode // 拿到父元素
const copyP = wrapper.querySelector('.copy-p') // 拿到父元素下面的 p
const copyInput = wrapper.querySelector('.copy-input') // 拿到父元素下面的 textarea
console.log(copyInput)
copyInput.value = copyP.innerHTML
copyInput.select()
document.execCommand('copy', true)
}
一个文档流中, id是唯一的, 同一id只能有一个, 换成class就可以了
