你可以」不要使用textareas作爲富文本編輯器。您不能將某些文字設爲粗體,而不能使其他文字爲空這是全部或沒有。
但是,您可以添加文本並將其選中。我添加了兩個按鈕,一個添加文本並選擇它,另一個添加'[b]文本[/ b]'並選擇'文本'。
PURE JS - 的jsfiddle:http://jsfiddle.net/seadonk/x3wkkqh4/3/
JQUERY - 的jsfiddle:http://jsfiddle.net/seadonk/x3wkkqh4/
PURE JS
(function() {
var btn = document.getElementById('formatBtn');
btn.onclick=function(){insertAndSelect();};
var btn2 = document.getElementById('formatBtnBolded');
btn2.onclick=function(){insertAndSelectBolded();};
})();
function insertAndSelect() {
var textarea = document.getElementById('content');
var texttoinsertvalue = document.getElementById('textToInsert').value;
var selectionStart = textarea.value.length;
textarea.value = textarea.value + texttoinsertvalue;
var selectionEnd = textarea.value.length;
selectRange(textarea,selectionStart, selectionEnd);
}
function insertAndSelectBolded() {
var textarea = document.getElementById('content');
var texttoinsertvalue = document.getElementById('textToInsert').value;
var selectionStart = textarea.value.length+3;
textarea.value = textarea.value + '[b]'+texttoinsertvalue+'[/b]';
var selectionEnd = textarea.value.length - 4;
selectRange(textarea,selectionStart, selectionEnd);
}
function selectRange(e, start, end){
if (!e) return;
else if (e.setSelectionRange) { e.focus(); e.setSelectionRange(start, end); } /* WebKit */
else if (e.createTextRange) { var range = e.createTextRange(); range.collapse(true);
range.moveEnd('character', end); range.moveStart('character', start); range.select(); } /* IE */
else if (e.selectionStart) { e.selectionStart = start; e.selectionEnd = end; }
}
JQUERY
$().ready(function() {
$('#formatBtn').click(function() {
insertAndSelect();
})
$('#formatBtnBolded').click(function() {
insertAndSelectBolded();
})
});
function insertAndSelect() {
var textarea = $('#content');
var selectionStart = textarea.val().length;
textarea.val(textarea.val() + $('#textToInsert').val());
var selectionEnd = textarea.val().length;
textarea.selectRange(selectionStart, selectionEnd);
}
function insertAndSelectBolded() {
var textarea = $('#content');
var selectionStart = textarea.val().length+3;
textarea.val(textarea.val() + '[b]'+$('#textToInsert').val()+'[/b]');
var selectionEnd = textarea.val().length-4;
textarea.selectRange(selectionStart, selectionEnd);
}
//use this function to set the range.
$.fn.selectRange = function(start, end) {
var e = document.getElementById($(this).attr('id'));
if (!e) return;
else if (e.setSelectionRange) { e.focus(); e.setSelectionRange(start, end); } /* WebKit */
else if (e.createTextRange) { var range = e.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', start); range.select(); } /* IE */
else if (e.selectionStart) { e.selectionStart = start; e.selectionEnd = end; }
};
你能澄清你的意思嗎?mark' – cmorrissey
@cmorrissey oops抱歉。選擇文字。我現在將其核實:) –
jQuery標籤的用途? –