【问题标题】:Paste selected text to another textarea将所选文本粘贴到另一个文本区域
【发布时间】:2021-03-14 09:09:41
【问题描述】:

纯 JS 是否可以将选定的文本粘贴到指定的 textarea 中?就我而言,我想在其中一个文本区域中选择文本,当按下 ctrl & A 时,选定的文本将粘贴到最后一个(V1)文本区域中。

我找到了类似的案例 (https://jsfiddle.net/QenBV/1/),但它只适用于 1 个输入文本区域,但我有大量的文本区域。

        function Addkey(e) {
            if (e.ctrlKey && e.keyCode == 65) {
                e.preventDefault();
                    document.execCommand("copy");
            }
        }
        
        document.addEventListener('keydown', Addkey, false);
<textarea>Text1</textarea><br/>
<textarea>Text2</textarea><br/>
<textarea>Text3</textarea><br/>

<p></p>
<hr/>
<p></p>

<textarea id="V1"></textarea><br/>

【问题讨论】:

  • 对多个&lt;textarea&gt; 做同样的事情不是问题。捕获ctrl/cmd + a 似乎是问题所在。这是一个硬性要求吗?
  • 一般来说,ctrl/cmd +a 不是硬性要求,但是按键是。为什么会出现这个问题?我认为按键是我的问题中最简单的部分。
  • 这里正在进行模糊处理:jsfiddle.net/na1396oq

标签: javascript html textarea clipboard


【解决方案1】:

您可以简单地使用 javascript/jquery 找到焦点文本字段,然后在选中时复制文本并将其连接到 V1 文本区域中的现有文本或者您可以简单地在文本字段的末尾添加一个按钮,当单击该按钮,您可以使用 javascript/jquery 查找每个文本字段的文本并将每个文本连接起来并粘贴到 v1 文本区域中

【讨论】:

  • 没有标点符号很难阅读整段,请您改进一下?谢谢。
【解决方案2】:

根据您的问题,以下是您要将文本复制给其他人的第一个文本区域

<textarea rows="5" cols="80" id="input" onkeyup="copySelected(event)" >One two three</textarea>

并且你想将选中的文本粘贴到下面的textarea的

<textarea rows="5" cols="80" id="selection" class="selection"></textarea>
<textarea rows="5" cols="80" id="selection1" class="selection"></textarea>
<textarea rows="5" cols="80" id="selection2" class="selection"></textarea>
<textarea rows="5" cols="80" id="selection3" class="selection"></textarea>
<textarea rows="5" cols="80" id="selection4" class="selection"></textarea>
<textarea rows="5" cols="80" id="selection5" class="selection"></textarea>
<textarea rows="5" cols="80" id="selection6" class="selection"></textarea>

这将是您的纯 JavaScript 代码。

<script>
function getSelectedText(el) {
    if (typeof el.selectionStart == "number") {
        return el.value.slice(el.selectionStart, el.selectionEnd);
    } else if (typeof document.selection != "undefined") {
        var range = document.selection.createRange();
        if (range.parentElement() == el) {
            return range.text;
        }
    }
    return "";
}

function copySelected(event) {

    if(event.ctrlKey && ())
    var srcTextarea = document.getElementById("input");
    var destTextarea = document.getElementsByClassName("selection");
    var txtd=getSelectedText(srcTextarea);
    <!-- if u want to paste the text only last one of your textarea -->
    
    destTextarea[destTextarea.length-1].value = txtd;
    
    <!-- if u want to paste the text all of the textarea then use following code block -->
    /*
     for(i=0; i<destTextarea.length; i++){
      destTextarea[i].value = txtd;
     }
    */

}

</script>

在这里,当您在第一个文本区域中按“ctrl + a”时,文本将被粘贴到所有其他文本区域中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    相关资源
    最近更新 更多