IE10增加了通过Document.execCommand()执行剪切,复制命令的功能.Chrome 43也支持这些命令.
浏览器中任意选中的文本都可以剪切或者复制到剪切板.
当这个功能与Selection API结合使用可以达到很好的效果.
本例将实现点击按钮复制邮件地址功能.demo
<div id="demo1">
<p>Email me at <a href="mailto:matt@example.co.uk" class="js-emaillink">matt@example.co.uk</a></p>
<p><button class="js-emailcopybtn"><img src="http://7xio0w.com1.z0.glb.clouddn.com/avatar.jpg" alt=""></button></p>
<script>
(function () {
var copyEmailBtn = document.querySelector('.js-emailcopybtn');
copyEmailBtn.addEventListener('click', function (event) {
// select the email link anchor text
var emailLink = document.querySelector('.js-emaillink');
var range = document.createRange();
range.selectNode(emailLink);
window.getSelection().addRange(range);
try {
// now that we've selected the anchor text, execute the copy command
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccess';
console.log('copy email command was ' + msg);
} catch (erro) {
console.log('unable to copy');
}
// Remove the selections - Note: Should use
// removeRange(range) when it is supported
window.getSelection().removeAllRanges();
});
}());
</script>
在javascript中为按钮添加了时间监听器,监听器选取js-emaillink
链接的邮件地址文本,然后执行复制命令将邮件地址复制到用户的剪切板,最后取消邮件地址的选中状态.
在上面的代码中我们使用了Selection API, window.getSelection()来设置链接文本的选取,这正是我们需要复制到剪切板的内容.在执行document.execCommand()
之后我们通过调用window.getSelection().removeAllRanges()解除文本选择状态.
如果需要确定一切都按照预期正常工作,可以检查document.execCommand()
返回值,当命令不支持或者被禁止时将返回false
.我们将execCommand()
调用包装在try-catch中是因为剪切和复制在某种情况下会抛出错误.
剪切命令可以在文本输入框中的文本.demo
<div id="demo2">
<p><textarea class="js-cuttextarea">Hello I'm some text</textarea></p>
<p><button class="js-textareacutbtn" disable>Cut Textarea</button></p>
<script>
(function () {
var cutTextareaBtn = document.querySelector('.js-textareacutbtn')
cutTextareaBtn.addEventListener('click', function (event) {
var cutTextarea = document.querySelector('.js-cuttextarea');
cutTextarea.select();
try {
var successful = document.execCommand('cut');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Cut text is ' + msg);
} catch (e) {
console.log('cut error');
}
}, false);
}());
</script>
</div>