HTML中简单制作点击某文字直接复制内容js
原理:
创建一个唯一的隐藏的可复制的元素,然后调用window.getSelection()获取选中内容,再使用document.execCommand("copy")执行copy
HTML部分
<p onclick="copyAble(this)">这里写可复制内容,也可以套用到按钮等</p>
调用JS部分
<script>
function copyAble(element) {
var id = 'copy-able-el'
var scrollTop = document.documentElement.scrollTop;
var copyElement = document.getElementById(id);
copyElement|| (copyElement= document.createElement("textarea"),
copyElement.style.position = "absolute",
copyElement.style.left = "-9999px",
copyElement.style.top = scrollTop + "px",
copyElement.id = id,
document.body.appendChild(copyElement)),
copyElement.textContent = element.innerText;
element = id;
if (element = "string" == typeof element ? document.querySelector(element) : element,
navigator.userAgent.match(/ipad|ipod|iphone/i)) {
var elementEditable = element.contentEditable , elementOnly = element.readOnly;
element.contentEditable = !0,
element.readOnly = !0;
var documentRange = document.createRange();
documentRange.selectNodeContents(element);
var selection = window.getSelection();
selection.removeAllRanges(),
selection.addRange(documentRange),
element.setSelectionRange(0, 999999),
element.contentEditable = elementEditable,
element.readOnly = elementOnly } else {
copyElement.select()
}
document.execCommand("copy")
}
</script>
JS放在<body>上方,使用onclick="copyAble(this)"标签属性进行调用,代码暂时没有添加复制成功提示功能,需要朋友请自行编辑js。点击相应文字后,直接复制到剪切板。手机电脑都可用。