我有这个小功能,允许用户选择标签。它没有做什么,当单击按钮时(Bold,Italic或Underline),它不会将光标放在两个标签之间(打开和关闭)。
function formatText(tag) {
var Field = document.getElementById('some-input');
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;
}
和
<a href="javascript:formatText('b')" class="small_button">Bold</a>
<a href="javascript:formatText('i')" class="small_button">Italic</a>
<a href="javascript:formatText('u')" class="small_button">Underline</a>
PS我尝试过几件事情都没有用。出于某种原因,我无法自己解决这个问题。
答案 0 :(得分:0)
这就是我想要的。所以这一切都很好。
<a class="small_button" id="b"><b>Bold</b></a>
<a class="small_button" id="i"><i>Italic</i></a>
<a class="small_button" id="u"><u>Underline</u></a>
<a class="small_button" id="l">Large</a>
使用Javascript:
function addTagSel(tag, idelm) {
var tag_type = new Array('<', '>'); // for BBCode tag, replace with: new Array('[', ']');
var txta = document.getElementById('some-input');
var start = tag_type[0] + tag + tag_type[1];
var end = tag_type[0] +'/'+ tag + tag_type[1];
var IE = /*@cc_on!@*/false; // this variable is false in all browsers, except IE
if (IE) {
var r = document.selection.createRange();
var tr = txta.createTextRange();
var tr2 = tr.duplicate();
tr2.moveToBookmark(r.getBookmark());
tr.setEndPoint('EndToStart',tr2);
var tag_seltxt = start + r.text + end;
var the_start = txta.value.replace(/[\r\n]/g,'.').indexOf(r.text.replace(/[\r\n]/g,'.'),tr.text.length);
txta.value = txta.value.substring(0, the_start) + tag_seltxt + txta.value.substring(the_start + tag_seltxt.length, txta.value.length);
var pos = txta.value.length - end.length; // Sets location for cursor position
tr.collapse(true);
tr.moveEnd('character', pos); // start position
tr.moveStart('character', pos); // end position
tr.select(); // selects the zone
}
else if (txta.selectionStart || txta.selectionStart == "0") {
var startPos = txta.selectionStart;
var endPos = txta.selectionEnd;
var tag_seltxt = start + txta.value.substring(startPos, endPos) + end;
txta.value = txta.value.substring(0, startPos) + tag_seltxt + txta.value.substring(endPos, txta.value.length);
// Place the cursor between formats in #txta
txta.setSelectionRange((endPos+start.length),(endPos+start.length));
txta.focus();
}
return tag_seltxt;
}
document.getElementById('b').onclick = function() {
var tag_seltxt = addTagSel('b');
return tag_seltxt;
}
document.getElementById('i').onclick = function() {
var tag_seltxt = addTagSel('i');
return tag_seltxt;
}
document.getElementById('u').onclick = function() {
var tag_seltxt = addTagSel('u');
return tag_seltxt;
}
document.getElementById('l').onclick = function() {
var tag_seltxt = addTagSel('h5');
return tag_seltxt;
};