在WordPress主题中添加一个复制按钮

WordPress评论461阅读模式

有时可能需要在WordPress主题中添加一个复制按钮,方便用户复制链接或验证码之类的,这里提供一段简单的复制代码,供参考。

html代码:

<div class="copy-box">
	<div class="quote">
		<p class="quoteText">准备复制的内容</p>
		<a class="sourceLink" href="https://zmingcx.com">准备复制的链接</a>
	</div>
	<div class="copy-to-clipboard">
		<button class="copy-btn" onclick="copyToClipboard()">复制</button>
	</div>
</div>

js代码:

<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>

代码实现同时复制一段文字和文字的超链接。

本站文章大部分始于原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

拖动滑块以完成验证