首页 > textarea插入ubb代码,怎样让光标移动到ubb代码中间

textarea插入ubb代码,怎样让光标移动到ubb代码中间

现在我现在一个textarea的中指定的地方插入ubb代码,如:

<texarea>大家好,点击这个链接去我的网站</textarea>

我要在“这个链接”和“去我的网站”之间插入link的ubb代码并将光标移动到“[link]”和“[/link]”之间
如:

<texarea>大家好,点击这个链接[link][/link]去我的网站</textarea>

这样方便用户输入自己的链接,怎样通过js实现?


使用selectionStart和selectEnd对象来访问光标,进一步信息可以阅读Selection对象的参考:
https://developer.mozilla.org/zh-CN/docs/Web/API/Selection

对于IE8以及之前的版本,使用TextRange对象
https://msdn.microsoft.com/en-us/library/ms535872(v=vs.85).aspx

var selectText () {
    var input = document.getElementById("inputBox");
    if (typeof x.selectionStart != "undefined") {
        input.selectionStart = 1;
        input.selectionEnd = 3;
        input.focus();
    } else {  // IE8及之前版本
        var inputRange = input.createTextRange();
        inputRange.moveStart("character", 1);
        inputRange.moveEnd("character", 2);
        inputRange.select();
    }
}
【热门文章】
【热门文章】