2011-12-01 30 views
0

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

回答

0

好的,因爲沒有人有答案,我擴展了我的研究並且多讀了100多個線程,這是個玩笑。

我發現下面的線程答案:

Why getting a text selection from textarea works when a button clicked but not when a "div" clicked (Internet Explorer)

How to prevent buttons to submit a form.

兩個在這裏stackoverflow.com,

以任何理由IE失去焦點移出textarea的時候一個按鈕以外的元素被點擊,在我的情況下,跨度看起來像一個帶有CSS的按鈕。但問題是,點擊一個按鈕提交表單,我不希望發生這種情況,這就是爲什麼我選擇屏蔽跨度。

因爲我使用的按鈕標籤來代替,而在onclick IE的行爲屬性添加:

<button onclick="formatString($('#textid')[0].'italic'); return false">Italic</button> 

唯一的問題與此解決方案是遵循,如果一個函數拋出一個異常提交表單的任何方式。所以我必須稍微改變一下代碼以避免異常。我的一個糟糕的代碼習慣。使代碼難以調試。

有關此鏈接的最後一個主題的更多信息。