我又寫了一個Jquery的插件-在光標位置插入或替換選中的內容(兼容各瀏覽器)

這是我在IE和Firefox下的演示效果:



不是我想再制造轮子,而是因为从网上找的几个函数都有问题,不是ie插入不正常就是firexfox不能达到预期效果,我怀疑这些程序员七拼八凑出代码来之后根本就没经过测试,所以我只好自己再重写了.
首先你要下載並調用jquery,這個你可以去jquery.com下載,然後引入以下的代碼即可:

如果要轉載本文請注明出處,免的出現版權紛爭,我不喜歡看到那種轉載了我的作品卻不注明出處的人QQ9256114

(function($){
    $.fn.insert=function(_m){
        var _o=$(this).get(0);
        if($.browser.msie){
            _o.focus();sel=document.selection.createRange();sel.text=_m;sel.select();
        }else if(_o.selectionStart || _o.selectionStart == '0'){
            var startPos=_o.selectionStart;var endPos=_o.selectionEnd;var restoreTop=_o.scrollTop;
            _o.value=_o.value.substring(0, startPos) + _m + _o.value.substring(endPos,_o.value.length);
            if (restoreTop>0){_o.scrollTop=restoreTop;}
            _o.focus();_o.selectionStart=startPos+_m.length;_o.selectionEnd=startPos+_m.length;
        }
    }
})(jQuery)


用法很簡單:

<input type='button' value='insert' onclick='$("#Content").insert("abc")'><br>
<textarea id='Content' name='Content' rows='13' style='width:100%'>繼續測試1</textarea>


posted @ 2011-05-20 21:41  已經停更  阅读(434)  评论(0编辑  收藏  举报