首页  >  问答  >  正文

使用拖放功能将超链接复制到剪贴板以便粘贴到其他位置

我对代码没有任何经验或知识。

我正在尝试为WordPress博客文章创建一个带有引用的卡片。

卡片上有一个按钮,用户可以直接将引用复制到剪贴板。

我还希望复制超链接:(来源)链接到我的网站。

我一直在通过GPT和重写来运行这段代码。但每次它只复制文本,甚至不尝试复制URL。

我在下面附上了代码,希望有人能帮助,因为我快疯了。

<style>
.card-box {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  border: 2px solid #0077B5;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.quote {
  margin-bottom: 20px;
}

.quote p {
  font-size: 18px;
  line-height: 1.4;
  color: #333333;
}

.quote a {
  display: block;
  margin-top: 10px;
  font-size: 14px;
  color: black;
  text-decoration: none;
}

.copy-to-clipboard {
  margin-bottom: 20px;
}

.copy-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  font-size: 16px;
  line-height: 1;
  color: #ffffff;
  background-color: #0077B5;
  border: 2px solid #0077B5;
  border-radius: 4px;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.copy-btn i {
  margin-right: 5px;
}

.signature {
  margin-top: 20px;
  font-size: 12px;
  font-style: italic;
  color: #777777;
}
</style>

<div class="card-box">
  <div class="quote">
    <p id="quoteText">在这里输入您的引用或统计数据</p>
    <a id="sourceLink" href="https://www.example.com">来源</a>
  </div>
  <div class="copy-to-clipboard">
    <button class="copy-btn" onclick="copyToClipboard()"><i class="fas fa-copy"></i> 复制统计数据</button>
  </div>
  <div class="signature">
    <p>Chad Wyatt</p>
  </div>
</div>

<script>
  function copyToClipboard() {
    const quote = document.querySelector('#quoteText').textContent;
    const sourceLink = document.querySelector('#sourceLink').getAttribute('href');
    const copiedText = `引用:${quote}\n来源:${sourceLink}`;
    
    const tempTextArea = document.createElement('textarea');
    tempTextArea.value = copiedText;
    document.body.appendChild(tempTextArea);
    tempTextArea.select();
    document.execCommand('copy');
    document.body.removeChild(tempTextArea);
    
    alert('带有来源链接的引用已复制到剪贴板!');
  }
</script>

P粉419164700P粉419164700276 天前359

全部回复(1)我来回复

  • P粉269847997

    P粉2698479972024-01-17 18:54:25

    我在这里尝试了你的代码 https://www.w3schools.com/html/tryit.asp?filename=tryhtml_default

    对我来说运行良好。

    回复
    0
  • 取消回复