2011-12-01 27 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> 

唯一的问题与此解决方案是遵循,如果一个函数抛出一个异常提交表单的任何方式。所以我必须稍微改变一下代码以避免异常。我的一个糟糕的代码习惯。使代码难以调试。

有关此链接的最后一个主题的更多信息。