(Javascript)execCommand(' copy')复制文本,但会增加额外的空白值

时间:2015-12-27 03:52:18

标签: javascript html

我整夜都在网上搜索如何使用execCommand(' copy')功能。最后,在https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en上找到了一个非常好的解决方案。然而,我的新困境是,当我按下从输入字段复制值的按钮时,它会为它添加额外的空白区域。因此,通过正常的复制/粘贴操作(Ctl + E和Ctl + V),输入值如下所示:

TESTTESTTESTTEST

但是当我按下按钮将输入值复制到剪贴板时,它看起来像这样:

TEST

TEST

TEST

TEST

如何删除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(); 
  };

<!DOCTYPE html>
<html>
<head>
<title>Customer Information</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>

<body>

<b>First Name:</b><input type = "text" id = "firstName"/><button onclick = "copyValueToClipBoard('firstName')">Copy to Clipboard</button>
<textarea rows="50" cols="50"></textarea>
<br>
 </body>
</html>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:3)

问题在于选择。 Window.getSelection通常适用于元素节点文本节点。在您的情况下,您正在选择整个输入节点,从而为您提供结果。对于普通节点,您只能选择文本节点,但输入不具有文本节点。

但输入有setSelectionRange方法,只允许选择值。使用selectionEnd属性,您可以选择整个值,但请注意整个节点。像这样:

&#13;
&#13;
function copyValueToClipBoard(containerid) {
var valueToBeCopied = document.getElementById(containerid);
valueToBeCopied.setSelectionRange(0, valueToBeCopied.selectionEnd)

  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(); 
  };
&#13;
<!DOCTYPE html>
<html>
<head>
<title>Customer Information</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>

<body>

<b>First Name:</b><input type = "text" id = "firstName"/><button onclick = "copyValueToClipBoard('firstName')">Copy to Clipboard</button>
<textarea rows="50" cols="50"></textarea>
<br>
 </body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

问题在于,您的范围就像选择从之前到之后的整个输入,因此您可以获得空白填充,就像您这样做一样。而是直接使用选择

以下是如何在不破坏用户可能做出的先前选择的情况下执行此操作

&#13;
&#13;
function contentsToClipboard(node) {
    var selection = window.getSelection(),
        range;
    // backup
    if (selection.rangeCount)
        range = selection.getRangeAt(0);
    // empty selection in your favourite way
    selection.removeAllRanges();
    // select input contents
    node.selectionStart = 0;
    node.selectionEnd = node.value.length;
    // copy
    try {
        console.log(
            'Copy command was ' + 
            ['un', ''][+document.execCommand('copy')] + 
            'successful'
        );
    } catch (err) {
        console.log('Oops, unable to copy');
    }
    // restore
    selection.removeAllRanges();
    if (range)
        selection.addRange(range);
}

window.addEventListener('load', function () {
    var foo = document.getElementById('foo');
    document.getElementById('bar').addEventListener('click', function (e) {
        contentsToClipboard(foo);
    });
});
&#13;
foo <input id="foo" type="text" value="fizzbuzz" /> bar <input id="bar" type="button" value="copy" />
&#13;
&#13;
&#13;

答案 2 :(得分:0)

最简单的方法是使用.trim()

答案 3 :(得分:0)

建议的解决方案对我不起作用,所以基于它我做了一个。它删除出现在复制行开头的空格。代码如下:

copy() {
    var element = document.getElementById("elementId") as HTMLInputElement;
    element.select();
    element.setSelectionRange(1, element.selectionEnd);
    document.execCommand('copy');
  }