我整夜都在网上搜索,想弄清楚如何使用execCommand(‘copy’)功能.最后,在https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en上找到了一个非常好的解决方案.然而,我的新困境是,当我按下从输入字段复制值的按钮时,它会为它添加额外的空白区域.因此,通过正常的复制/粘贴操作(Ctl E和Ctl V),输入值如下所示:
TESTTESTTESTTEST
但是当我按下按钮将输入值复制到剪贴板时,它看起来像这样:
测试
测试
测试
测试
如何删除execCommand(‘copy’)添加到输入字段值的额外空格.我试过.replace(“”,“”);但这不起作用.我不确定如何继续.这是代码:
function copyValuetoClipBoard(containerid) {
var valuetoBecopied = document.getElementById(containerid);
var range = document.createrange();
range.selectNode(valuetoBecopied);
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' : 'unsuccessful';
console.log('copy email command was ' + msg);
} catch(err) {
console.log('Oops,unable to copy');
}
// Remove the selections - NOTE: Should use
// removeRange(range) when it is supported
window.getSelection().removeAllRanges();
};
informationMeta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
irst Name:irstName"/>
最佳答案
问题在于选择. Window.getSelection通常适用于元素节点和文本节点.在您的情况下,您正在选择整个输入节点,从而为您提供结果.对于普通节点,您只能选择文本节点,但输入没有文本节点.
但是输入有setSelectionRange方法,它允许只选择值.使用selectionEnd属性,您可以选择整个值,但请注意整个节点.像这样:
function copyValuetoClipBoard(containerid) {
var valuetoBecopied = document.getElementById(containerid);
valuetoBecopied.setSelectionRange(0,valuetoBecopied.selectionEnd)
try {
// Now that we've selected the anchor text,unable to copy');
}
// Remove the selections - NOTE: Should use
// removeRange(range) when it is supported
window.getSelection().removeAllRanges();
};
informationMeta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
irst Name:irstName"/>
原文地址:https://www.jb51.cc/html/426198.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。