jQuery在textarea中包装选定的文本

时间:2022-11-29 11:14:38

How can I get the user selected text(just inside textarea) and apply actions to it something like wrap the selection [#bold]selected text[/bold].

如何获取用户选择的文本(仅在textarea内)并对其应用操作,如包装选择[#bold]所选文本[/ bold]。

2 个解决方案

#1


22  

Building off what Soufiane posted, here's the code translated to jquery with the ability to pass in the open and close tags:

建立Soufiane发布的内容,这里的代码转换为jquery,能够传递开放和关闭标记:

function wrapText(elementID, openTag, closeTag) {
    var textArea = $('#' + elementID);
    var len = textArea.val().length;
    var start = textArea[0].selectionStart;
    var end = textArea[0].selectionEnd;
    var selectedText = textArea.val().substring(start, end);
    var replacement = openTag + selectedText + closeTag;
    textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}

Usage would then be like so:

用法就是这样:

wrapText("myTextArea", "[#bold]", "[/bold]");

#2


6  

function wrapAsLink(url){
  var textarea = document.getElementById("myTa");
  var len = textarea.value.length;
  var start = textarea.selectionStart;
  var end = textarea.selectionEnd;
  var sel = textarea.value.substring(start, end);
  var replace = '<a href="'+url+'">' + sel + '</a>';
  textarea.value = textarea.value.substring(0,start) + replace +
  textarea.value.substring(end,len);
}

This function may help you to do what you want with some tweaks. I found it here.

此功能可以帮助您通过一些调整来做您想做的事情。我在这里找到了。

#1


22  

Building off what Soufiane posted, here's the code translated to jquery with the ability to pass in the open and close tags:

建立Soufiane发布的内容,这里的代码转换为jquery,能够传递开放和关闭标记:

function wrapText(elementID, openTag, closeTag) {
    var textArea = $('#' + elementID);
    var len = textArea.val().length;
    var start = textArea[0].selectionStart;
    var end = textArea[0].selectionEnd;
    var selectedText = textArea.val().substring(start, end);
    var replacement = openTag + selectedText + closeTag;
    textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}

Usage would then be like so:

用法就是这样:

wrapText("myTextArea", "[#bold]", "[/bold]");

#2


6  

function wrapAsLink(url){
  var textarea = document.getElementById("myTa");
  var len = textarea.value.length;
  var start = textarea.selectionStart;
  var end = textarea.selectionEnd;
  var sel = textarea.value.substring(start, end);
  var replace = '<a href="'+url+'">' + sel + '</a>';
  textarea.value = textarea.value.substring(0,start) + replace +
  textarea.value.substring(end,len);
}

This function may help you to do what you want with some tweaks. I found it here.

此功能可以帮助您通过一些调整来做您想做的事情。我在这里找到了。