转JS--通过按钮直接把input或者textarea里的值复制到粘贴板里

时间:2021-08-26 13:45:55

document.activeElement属性为HTML 5中新增的document对象的一个属性,该属性用于返回光标所在元素。当光标未落在页面中任何元素内时,属性值返回body元素。

setSelectionRange(start, end) 设置选中文本起始位置与结束位置

execCommand方法是执行一个对当前文档,当前选择或者给出范围的命令

    点击按钮复制textarea文本框中内容

<script type="text/javascript">
function copyTextAreaCt()
{
var oContent=document.getElementById("content");
oContent.select(); // 选择对象
document.execCommand("Copy"); // 执行浏览器复制命令
alert("复制完毕,可粘贴");
}
</script>
<textarea cols="20" rows="10" id="content" value="">This is a paragraph......</textarea>
<input type="button" onClick="copyTextAreaCt()" value="点击复制代码" />

    转 通过按钮直接把input或者textarea里的值复制到粘贴板里

function copyToClipboard(elem) {
// create hidden text element, if it doesn't already exist
var targetId = "_hiddenCopyText_";
var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
var origSelectionStart, origSelectionEnd;
if (isInput) {
// can just use the original source element for the selection and copy
target = elem;
origSelectionStart = elem.selectionStart; //selectionStart光标的开始位置
origSelectionEnd = elem.selectionEnd; //selectionEnd 光标的结束位置
} else {
// must use a temporary form element for the selection and copy
target = document.getElementById(targetId);
if (!target) {
var target = document.createElement("textarea");
target.style.position = "absolute";
target.style.left = "-9999px";
target.style.top = "0";
target.id = targetId;
document.body.appendChild(target);
}
target.textContent = elem.textContent;
}
// select the content
var currentFocus = document.activeElement;//获取当前页面活动的元素
target.focus();
target.setSelectionRange(0, target.value.length); // copy the selection
var succeed;
try {
succeed = document.execCommand("copy");
} catch(e) {
succeed = false;
}
// restore original focus
if (currentFocus && typeof currentFocus.focus === "function") {
currentFocus.focus();
} if (isInput) {
// restore prior selection 恢复之前的选择
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// clear temporary content
target.textContent = "";
}
return succeed;
} //直接调用这个方法:
copyToClipboard(document.getElementById("name"));

文章转自  http://blog.csdn.net/qq377751971/article/details/65446247

http://www.cnblogs.com/tylerdonet/p/4533782.html

http://showlike.iteye.com/blog/1073642