页面布局分析:
按钮在文本框里面,所以文本框是父元素,按钮是子元素。要使得按钮在文本框的右上角,需要使用绝对定位。
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>#copy-text {background-color: black;width: 500px;height: 500px;color: white;position: relative;}#copy-btn {position: absolute;right: 0;}</style>
</head><body><div id="copy-text"><button id="copy-btn">复制</button><div id="code">示例代码</div></div><script src="jquery-3.6.4.min.js"></script><script>var copyBtn = $('#copy-btn');$('#copy-text').mouseenter(function() {//显示复制按钮copyBtn.show();});$('#copy-text').mouseleave(function() {//隐藏复制按钮copyBtn.hide();});const copyBtn2 = document.getElementById('copy-btn');const copyText = document.getElementById("copy-text");const code = document.getElementById("code");copyBtn2.addEventListener('click', function() {navigator.clipboard.writeText(code.innerText).then(() => {console.log("文本已复制到剪贴板");}).catch((err) => {console.error("无法复制文本:", err);});});</script>
</body></html>