我只是尝试用另一个文本替换输入字段中的选定文本,例如文本区域。
例如。如果我选择输入字段中的一部分文本并单击按钮 CENTER
,则所选文本应包含在 <center></center>
中.
我发现这个“solution”从 2009 年开始似乎已经过时了,我在 Chrome 和 Firefox 上试过了,我得到的信息是我的浏览器不受支持。
还有其他方法可以实现吗?它应该至少适用于 Firefox 和 Chrome。
最佳答案
试试这个:
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;
}
关于javascript - 单击按钮替换输入字段中的选定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39389522/