这里我们再来一次。我一直在寻找一整天为这个问题的解决方案......在IE冲突中使用createRange()
我的代码:
var formatString = function(t,style){
var el = $(t);
var pre;
var start;
var end;
var len;
var replace;
switch(style){
case 'italic':
pre = '[em]';
break;
case 'bold':
pre = '[b]';
break;
case 'paragraph':
pre = '[p]';
break;
}
if(document.selection){
el.focus();
var sel = document.selection.createRange();
// Finally replace the value of the selected text with this new replacement one
sel.text = pre + sel.text + pre.replace(/(\[)/,'[/');
} else {
len = el.val().length;
start = t.selectionStart;
end = t.selectionEnd;
sel = el.val().substring(start, end);
replace = pre + sel + pre.replace(/(\[)/,'[/');
el.val(el.val().substring(0,start) + replace + el.val().substring(end,len));
}
}
我在做什么是创建一个简单的所见即所得的只是一些格式化添加到文本这显然是处理,以显示正确的HTML标签。当然,所有浏览器都可以使用IE浏览器。
发生的问题是,当您在textarea外单击时,心爱的IE取消选择任何选定的文本。这导致对象sel.text没有文本。
我运行函数是这样的:
<button onclick="formatString($('#textid')[0],'italic')">Italic</button>
当您单击按钮其他浏览器输出
'the italic text' // output the [em]italic[/em] text - when italic is selected
IE output 'the [em][/em]italic text'
如果这是另一个线程只是引导我到它一样的,从字面上我有阅读200多个线程,并没有指出这个问题。