在我的 Ionic 应用程序上,我有一个文本区域,用户可以在其中选择文本并使用按钮 [BOLD] 在所选内容周围添加 [b] [/b]。
如何应用粗体格式,替换输出文本上的 [b] [/b]?
那是我的代码。这是 JsFiddle
<textarea id="TheTextInput" rows="5"></textarea>
<input type="button" id="TheButton" value="click" />
<input type="button" id="bold" value="BOLD" />
<pre id="TheOutput"></pre>
$(document).ready(function () {
$('#TheButton').click(PutTextIntoDiv);
});
function PutTextIntoDiv() {
var TheText = encodeURIComponent($('#TheTextInput').val());
$('#TheOutput').text(decodeURIComponent(TheText));
}
$( "#bold" ).click(function() {
var textArea = document.getElementById("TheTextInput");
if (typeof(textArea.selectionStart) != "undefined") {
var begin = textArea.value.substr(0, textArea.selectionStart);
var selection = textArea.value.substr(textArea.selectionStart, textArea.selectionEnd - textArea.selectionStart);
var end = textArea.value.substr(textArea.selectionEnd);
textArea.value = begin + '[b]' + selection + '[/b]' + end;
}
});
感谢您的帮助!!
*它与 Is it possible to display bold and non-bold text in a textarea? 不重复
因为我不想格式化文本区域内的文本,而是格式化输出文本。
最佳答案
考虑PutTextIntoDiv()
替换为:
function PutTextIntoDiv() {
$('#TheOutput').html($('#TheTextInput').val().replace(/\[b\]/g, '<b>').replace(/\[\/b\]/g, '</b>'));
}
<pre>
在你的 JSFiddle 中应该呈现 <b>
美好的。
关于javascript - 替换 [b][/b] 以在 DIV 上应用粗体文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40219674/