【问题标题】:Replace selected text from input fields on button click单击按钮时替换输入字段中的选定文本
【发布时间】:2017-01-16 07:16:10
【问题描述】:
我只是尝试用另一个文本替换来自输入字段(例如来自文本区域)的选定文本。
例如。如果我在输入字段中选择部分文本并单击按钮CENTER,则所选文本应包含在<center></center> 中。
我发现这个 2009 年的“solution”似乎已经过时了,我用 Chrome 和 Firefox 进行了尝试,但我得到了我的浏览器不受支持的信息。
还有其他方法可以实现吗?它至少应该适用于 Firefox 和 Chrome。
【问题讨论】:
标签:
javascript
jquery
google-chrome
firefox
【解决方案1】:
试试这个:
function getSel() // javascript
{
console.log("test");
// obtain the object reference for the textarea>
var txtarea = document.getElementById("mytextarea");
// obtain the index of the first selected character
var start = txtarea.selectionStart;
// obtain the index of the last selected character
var finish = txtarea.selectionEnd;
//obtain all Text
var allText = txtarea.value;
// obtain the selected text
var sel = allText.substring(start, finish);
//append te text;
var newText=allText.substring(0, start)+"<center>"+sel+"</center>"+allText.substring(finish, allText.length);
console.log(newText);
txtarea.value=newText;
}
https://jsfiddle.net/qpw1eemr/1/
【解决方案2】:
这是一个简单的例子
$(function() {
$('textarea').select(function(event) {
var elem = $(this);
var start = elem.prop("selectionStart");
var end = elem.prop("selectionEnd");
var prefixStr = elem.text().substring(0, start);
var sufixStr = elem.text().substring(end, elem.text().length);
var selectedStr = elem.text().substring(start, end);
function transform(str) {
return '<center>' + str + '</center>'
}
elem.text(prefixStr + transform(selectedStr) + sufixStr);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii</textarea>
【解决方案3】:
// hope this would be usefull
// i used these codes for auto completing the texts in textarea.
// other methods change all matching items before the selected text
// but this affects only the text where caret on.
// at first, i divided textarea.value into 3 pieces. these are ;
// p1; until the 'searched' item, p2 after 'searched' item
// and pa = new item that will replaced with 'searched' item
// then, i combined them together again.
var tea = document.getElementById(targetTextArea);
caretPosition = tea.selectionStart - ara.length; //ara=searched item
p1 = tea.value.substring(0,caretPosition);
console.log('p1 text : ' + p1);
p2 = tea.value.substring(caretPosition+ara.length,tea.value.length);
console.log('p2 text : ' + p2);
pa = yeni; //new item
console.log('pa text : ' + pa);
tea.value = p1 + pa + p2;
tea.selectionStart = caretPosition + yeni.length;
tea.selectionEnd = caretPosition + yeni.length;
tea.focus();