點選按鈕拷貝複製元素內文字程式碼例項

antzone發表於2017-04-17

分享一段程式碼例項,它實現了點選按鈕拷貝指定元素內文字的功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script>
function copyArticle(event){
  const range = document.createRange();
  range.selectNode(document.getElementById('article'));
 
  const selection = window.getSelection();
  if(selection.rangeCount > 0) selection.removeAllRanges();
  selection.addRange(range);
  document.execCommand('copy');
}
window.onload = function () {
  var obt = document.getElementById("copy");
  obt.addEventListener('click', copyArticle, false);
 
}
</script>
</head>
<body>
<article id="article">螞蟻部落歡迎您,本站的url地址是www.softwhy.com</article>
<input type="button" value="點選複製" id="copy"/>
</body>
</html>

相關文章