【备忘】HTML实现点击复制元素⽂字
借鉴CSDN源码⾥的点击复制代码(就CSDN代码块右上⾓的复制按钮),其⼤概思路是创建⼀个唯⼀的隐藏的可复制的元素,然后调⽤Selection()获取选中内容,再使⽤Command("copy")执⾏copy。完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
html document是什么<meta charset="UTF-8">
<meta name="viewport"content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible"content="ie=edge">
<title>复制⽂字</title>
</head>
<body>
<p onclick="copyAble(this)">点我!我是复制内容。</p>
<script>
/**
* 可复制的。
* @param {Document} element
*/
function copyAble(element){
var id ='copy-able-el'
var scrollTop = document.documentElement.scrollTop;
var copyElement = ElementById(id);
copyElement||(copyElement= ateElement("textarea"),
copyElement.style.position ="absolute",
copyElement.style.left ="-9999px",
p = scrollTop +"px",
copyElement.id = id,
document.body.appendChild(copyElement)),
element = id;
if(element ="string"==typeof element ? document.querySelector(element): element,
navigator.userAgent.match(/ipad|ipod|iphone/i)){
var elementEditable = tEditable
,
elementOnly = adOnly;
var documentRange = ateRange();
documentRange.selectNodeContents(element);
var selection = Selection();
selection.addRange(documentRange),
element.setSelectionRange(0,999999),
}else{
copyElement.select()
}
}
</script>
</body>
</html>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。