javascript将textarea中的选定文本

时间:2018-07-31 07:03:11

标签: javascript html css

我试图为我的textarea做一个简单的BB代码。我的代码工作正常,但不接受选定的文本。示例:TEXT。如果我在TEXT ant上用鼠标选择,请选择[B]标签,它不会将文本更新为:[b] TEXT [/ b]。它写在TEXT之后。示例:TEXT [b] [/ b]。有什么建议吗?

FROM mariadb
COPY . /usr/src/app
WORKDIR /usr/src/app
# I will be performing a phpmyadmin installation in this script
RUN setup.sh
CMD service mysql start && service apache2 start

2 个答案:

答案 0 :(得分:1)

您只是在最后添加标签,但您希望标签包裹所选文本。然后,您可以这样做。另外,相应地编辑HTML代码。

function formatText(tag) {
   var Field = document.getElementById('text');
   var val = Field.value;
   var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
   var before_txt = val.substring(0, Field.selectionStart);
   var after_txt = val.substring(Field.selectionEnd, val.length);
   Field.value = before_txt+'['+tag+']' +selected_txt +'[/' +tag+']' + after_txt;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<a href="#" class="btn hint--bottom" aria-label="Bold Text" onclick="formatText ('b');"><i class="fas fa-bold">Click</i></a>
  <textarea id="text">I trying todo a simple BB code for my textarea. My code works fine, but it not takes selected text. Example: TEXT. If i select with mouse on TEXT ant choose the [B] tag it does not update text to: [b]TEXT[/b]. It writes after TEXT. Example: TEXT[b][/b]. Any suggest?</textarea>
  </body>
</html>

答案 1 :(得分:1)

首先分割标记,以便我们得到[b]和[/ b] 您其余的代码很好。

在这里https://jsfiddle.net/x0tfyna9/12/在Chrome上进行了测试

<body>
<textarea id="text"></textarea>
<a href="#" onclick="formatText('[b][/b]');"><i class="fas fa-bold">xasada</i></a>
<script> 
function formatText(tag) {
  var tags = tag.split("]", 2).map(function(t) {
    return t + "]";
  });
  var Field = document.getElementById('text');
  var val = Field.value;
  var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
  var before_txt = val.substring(0, Field.selectionStart);
  var after_txt = val.substring(Field.selectionEnd, val.length);
  Field.value = before_txt + tags[0] + selected_txt + tags[1] + after_txt;
}
</script> 
</body>