我正在尝试制作一个简单的 ubb 编辑器,但 document.selection.createRange() 在 IE 中不起作用,它不会得到任何突出显示的文本(尝试提醒突出显示的文本但什么也得不到)。我仍然无法找到原因并解决此问题。
window.onload = function () {
var ubb = document.getElementById('ubb_code');
var ubba = ubb.getElementsByTagName('a');//ubb buttons
var textarea = document.getElementsByTagName('textarea')[0];//editable textarea filed
//onclick to insert ubbcode
ubba[0].onclick = function() {
tag('[b]','[/b]');
};
//function used to insert ubbcode
function tag(tag1,tag2){
// code for IE
if (document.selection){
textarea.focus();
var sel = textarea.document.selection.createRange();//It DOES NOT work!
//alert(sel.text);
sel.text = tag1 + sel.text + tag2;
}else{
// code for none-IE webbrowsers
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var scrollTop = textarea.scrollTop;
var scrollLeft = textarea.scrollLeft;
var sel = textarea.value.substring(start, end);
//alert(sel);
var rep = tag1 + sel + tag2;
textarea.value = textarea.value.substring(0,start) + rep + textarea.value.substring(end,len);
textarea.scrollTop = scrollTop;
textarea.scrollLeft = scrollLeft;
}
}