Selection
window.getSelection():當(dāng)前文本選擇的范圍
Selection.toString
setSelectionRange:
inputElement.setSelectionRange(selectionStart,selectionEnd,selectionDirection):選擇特定區(qū)域
<p><input type="text" id="mytextbox" size="20" value="這是一段等待選擇的文字">
<p><button onclick="SelectText()">選擇</button></p>
function SelectText () {
var input = document.getElementById("mytextbox");
input.focus();
input.setSelectionRange(0,-1); //代表全選
}
Document.execCommand
bool = document.execCommand(aCommandName,aShowDefaultUI,aValueArgument)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p>
微專(zhuān)業(yè)由網(wǎng)易云音樂(lè)、郵箱大師、網(wǎng)易嚴(yán)選、考拉海購(gòu)一線前端產(chǎn)品開(kāi)發(fā)專(zhuān)家聯(lián)手打造,聚焦頁(yè)面制作、JavaScript程序設(shè)計(jì)、DOM編程藝術(shù)四大前端工程師必備知識(shí)技
</p>
<input type="text" name="inputText" id="inputText" value="這是一段需要被復(fù)制的文本"/>
<input type="button" name="btn" id="btn" value="copy"/><br/>
<p>
<textarea id="textarea" rows="3"></textarea>
</p>
<script type="text/javascript">
var btn = document.getElementById('btn');
btn.addEventListener('click', function(){
var inputText = document.getElementById('textarea');
inputText.value = window.getSelection().toString();
var x = document.activeElement;
inputText.focus();
inputText.setSelectionRange(0,inputText.value.length);
document.execCommand('copy',true);
x.focus();
});
</script>
</body>
</html>
兼容性
IE9+