gpt4 book ai didi

javascript - 将所选文本从一个文本区域复制到另一个文本区域

转载 作者:搜寻专家 更新时间:2023-11-01 04:55:40 25 4
gpt4 key购买 nike

我有两个 <textarea>秒。一个是 id="input"另一个是id="selection" .

<textarea id="input">将包含一些 HTML。用户将在此文本区域中选择一些文本,单击一个按钮,所选文本将被复制到 <textarea id="selection"> .

我可以使用 jQuery 或纯 JavaScript,我希望它能在 IE7+、Safari 和 Firefox 中运行。

最佳答案

我只有一种方法可以做到。正如您可能知道的那样,您遇到的问题是当您单击按钮(从而触发事件以复制选择)时,文本区域失去焦点,因此没有文本被选中。

因此,作为一种变通方法,我将 div 样式设置为看起来(有点)像文本区域。这似乎有效:

<style type="text/css">
.textarea {
border:1px solid black;
width:200px;
height:100px;
overflow-y: auto;
float:left;
}
</style>

然后标记看起来像这样:

<div id="input" class="textarea">This is a test</div>
<textarea id="selection"></textarea>

<button id="theButton">Copy</button>

最后,脚本:

var selText = "";

$( document ).ready( function() {
$( '#theButton' ).mousedown( function() {
$( '#selection' ).val( getSelectedText() );
});
});

function getSelectedText(){
if ( window.getSelection ) {
return window.getSelection().toString();
}
else if ( document.getSelection ) {
return document.getSelection();
} else if ( document.selection ) {
return document.selection.createRange().text;
}
}

为了给予应有的评价,我从 http://esbueno.noahstokes.com/post/92274686/highlight-selected-text-with-jquery 获得了 getSelectedText() 方法

关于javascript - 将所选文本从一个文本区域复制到另一个文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4342229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com