javascript - 单击按钮替换输入字段中的选定文本

标签 javascript jquery google-chrome firefox

我只是尝试用另一个文本替换输入字段中的选定文本,例如文本区域。 例如。如果我选择输入字段中的一部分文本并单击按钮 CENTER ,则所选文本应包含在 <center></center> 中.

我发现这个“solution”从 2009 年开始似乎已经过时了,我在 Chrome 和 Firefox 上试过了,我得到的信息是我的浏览器不受支持。

还有其他方法可以实现吗?它应该至少适用于 Firefox 和 Chrome。

Textarea

enter image description here

最佳答案

试试这个:

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/

关于javascript - 单击按钮替换输入字段中的选定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39389522/

相关文章:

javascript - Firebase getDownloadURL 从存储无法设置 Img Src

javascript - 在 SailsJS 中将图像 URL 保存到用户

javascript - 如何使列表元素可编辑

javascript - window.opener 为空...以前不是

Ajax 不发布数据,Chrome 扩展

html - Webkit 过渡在 chrome 中有效,但在 firefox 中无效

javascript - mLab : Find all users getting db object instead of records

javascript - 如何在 Javascript 中保存带有换行符的 cookie?

jQuery。在远程服务器上使用json数据失败

javascript - 调用 Instagram 用户 API 时发生错误。刚刚死在 GET 方法中