天天看點

javascript實作textarea中光标處插入字元的實作[相容ie和firefox](來自網絡)

 因項目需要,需要在多行文本框中的光标位置插入字元,利于js的 document.selection屬性很快就實作,但發現在firefox中無法相容selection屬性,網上找了很久也沒有找到合适的方法,經過研究,改出了相容ie和FF的完美解決方案

代碼如下:

<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> function AddText(str) { var ubb = document.getElementById( " TxtContent " ); var ubbLength = ubb.value.length; ubb.focus(); if ( typeof document.selection != " undefined " ) { document.selection.createRange().text = str; } else { ubb.value = ubb.value.substr( 0 ,ubb.selectionStart) + str + ubb.value.substring(ubb.selectionStart,ubbLength); } }

例如:

<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> function Underline() { var tUnderline = prompt( " 請輸入要設定的下劃線文字\n标簽:[u][/u] " , "" ) if (tUnderline == "" || tUnderline == null ) { return ; } tUnderline = " [u] " + tUnderline + " [/u] " AddText(tUnderline); }

HTML部分:

<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> < a href ="javascript:Underline();void(0)" >< img src ="Images/Style/underline.gif" alt ="下線線" border ="0" /></ a >

注:1、TxtContent為textarea的ID,函數str參數為要插入的字元

2、在ie6.0和FF2.0中調試通過!!   

繼續閱讀