将所选文本从一个文本区域复制到另一个文本区域 [英] Copy selected text from one textarea to another
本文介绍了将所选文本从一个文本区域复制到另一个文本区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个< textarea>
s。一个 id =input
,另一个 id =selection
。
I have two <textarea>
s. One with id="input"
and the other with id="selection"
.
< textarea id =input>
将包含一些HTML。用户将在此文本区域中选择一些文本,单击按钮,所选文本将被复制到< textarea id =selection>
。
<textarea id="input">
will contain some HTML. The user will select some text in this textarea, click a button and the selected text will be copied to <textarea id="selection">
.
我可以使用jQuery或只是vanilla JavaScript,我希望它可以在IE7 +,Safari和Firefox中使用。
I can use jQuery or just vanilla JavaScript and I'd like it to work in IE7+, Safari and Firefox.
推荐答案
以下将执行此操作:
查看实际操作: http://www.jsfiddle.net/QenBV/1/
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() {
var srcTextarea = document.getElementById("input");
var destTextarea = document.getElementById("selection");
destTextarea.value = getSelectedText(srcTextarea);
}
<input type="button" onclick="copySelected()" value="copy selected">
这篇关于将所选文本从一个文本区域复制到另一个文本区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文