Selection
window.getSelection():当前文本选择的范围
Selection.toString
setSelectionRange:
inputElement.setSelectionRange(selectionStart,selectionEnd,selectionDirection):选择特定区域
<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>
微专业由网易云音乐、邮箱大师、网易严选、考拉海购一线前端产品开发专家联手打造,聚焦页面制作、JavaScript程序设计、DOM编程艺术四大前端工程师必备知识技
</p>
<input type="text" name="inputText" id="inputText" value="这是一段需要被复制的文本"/>
<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+
网友评论