[英]Using createRange() in IE conflict
再來一次。 我整天都在尋找解決這個問題的方法...
我得到了代碼:
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之外,所有其他瀏覽器都可以正常工作。
發生的問題是,當您在文本區域之外單擊時,心愛的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多個線程,沒有任何內容指出此問題。
好的,因為沒人能回答,所以我擴大了研究范圍並閱讀了100多個主題,這是個玩笑。
我在以下線程中找到了答案:
為什么在單擊按鈕時從textarea中獲取文本選擇有效,但單擊“ div”時卻無效(Internet Explorer)
兩者都在stackoverflow.com中,
由於任何原因,當單擊按鈕以外的元素時,IE都會失去對文本區域的關注,在我的情況下,跨度看起來像是帶有CSS的按鈕。 但是問題是單擊按鈕提交表單,而我不希望這樣發生,這就是為什么我選擇掩蓋跨度。
由於IE行為,我改用button標記,並在onclick屬性中添加:
<button onclick="formatString($('#textid')[0].'italic'); return false">Italic</button>
此解決方案的唯一問題如下,如果函數引發異常,則以任何方式提交表單。 因此,我必須對代碼進行一些更改以避免出現異常。 我的不良代碼習慣。 使代碼難以調試。
有關更多信息,請參見鏈接的最后一個線程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.