javascript在光标位置插入内容

加载中……

之前我写过一篇文章是通过javascript获取光标的位置——javascript获取光标位置以及设置光标位置。由于产品需要在留言板的光标处上插入表情,这样就用到了javascript在光标位置插入内容的功能了~其实原理很简单,IE下可以通过document.selection.createRange();来实现,而Firefox(火狐)浏览器则需要首先获取光标位置,然后对value进行字符串截取处理。不多说了~直接上我写的一个jQuery在光标位置插入内容插件吧~

jQuery在光标位置插入内容插件代码

(function($){
	$.fn.extend({
		insertAtCaret: function(myValue){
			var $t=$(this)[0];
			if (document.selection) {
				this.focus();
				sel = document.selection.createRange();
				sel.text = myValue;
				this.focus();
			}
			else 
				if ($t.selectionStart || $t.selectionStart == '0') {
					var startPos = $t.selectionStart;
					var endPos = $t.selectionEnd;
					var scrollTop = $t.scrollTop;
					$t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
					this.focus();
					$t.selectionStart = startPos + myValue.length;
					$t.selectionEnd = startPos + myValue.length;
					$t.scrollTop = scrollTop;
				}
				else {
					this.value += myValue;
					this.focus();
				}
		}
	})	
})(jQuery);

使用方法

$(selector).insertAtCaret("value");
2010年5月13日
首页 > JavaScript > javascript在光标位置插入内容

相关文章

评论( 6 )
  1. taxuewuhen 2010年5月14日 21:54  | #1 沙发!

    博主,想问一下你的空间和域名哪里买的,貌似是国外的,我也想买一个

  2. taxuewuhen 2010年5月14日 22:27  | #2 板凳

    @断桥残雪
    你找代理买的还是自己买的

  3. bestdong 2010年5月15日 04:36  | #3

    Dear, 断桥残雪

    一定要有博客吗?独立只安装一个爱墙可以吗?

    Your sincerely,

  4. 民族证券 2010年5月21日 10:29  | #4

    朋友推荐过来的…文章有深度.

  5. 皇家元林 2010年5月23日 22:05  | #5

    很短的域名啊
    这个IN域名价格不菲啊

  6. 断桥残雪 2010年5月14日 22:08  | #6

    空间是dreamhost,域名是godaddy的~

容许使用的 HTML 标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">
Trackbacks & Pingbacks ( 0 )