這裏我們再來一次。我一直在尋找一整天爲這個問題的解決方案......在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多個線程,並沒有指出這個問題。